<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\Affiliate;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class TrackAffiliateReferral
{
    public function handle(Request $request, Closure $next): Response
    {
        $refCode = $request->query('ref');

        if (is_string($refCode) && $refCode !== '') {
            $affiliate = Affiliate::where('referral_code', $refCode)
                ->where('status', 'active')
                ->first();

            if ($affiliate) {
                $response = $next($request);

                $cookieLifetime = (int) config('affiliate.cookie_lifetime_days', 30) * 60 * 24;

                if ($response instanceof \Illuminate\Http\Response || $response instanceof \Illuminate\Http\RedirectResponse) {
                    $response->withCookie(cookie(
                        'affiliate_id',
                        (string) $affiliate->id,
                        $cookieLifetime,
                    ));
                }

                return $response;
            }
        }

        return $next($request);
    }
}
