<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class ScreenshotAuthMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $this->isEnabled()) {
            return $next($request);
        }

        $token = $request->query('_screenshot_token');

        if (! $token || ! is_string($token) || ! $this->isValidToken($token)) {
            return $next($request);
        }

        if (Auth::check()) {
            return $next($request);
        }

        $user = $this->getUserForDomain($request);

        if (! $user) {
            return $next($request);
        }

        Log::info('Screenshot authentication bypass used', [
            'user_id' => $user->id,
            'user_email' => $user->email,
            'domain' => $request->getHost(),
            'path' => $request->path(),
            'ip' => $request->ip(),
        ]);

        Auth::login($user);

        return $next($request);
    }

    private function isEnabled(): bool
    {
        return config('app.env') === 'local'
            || config('app.screenshot_auth_enabled', false);
    }

    private function isValidToken(string $token): bool
    {
        $validToken = config('app.screenshot_token');

        return $validToken && hash_equals($validToken, $token);
    }

    private function getUserForDomain(Request $request): ?User
    {
        $host = $request->getHost();

        if ($host === config('app.domains.admin')) {
            return User::role('admin')->first();
        }

        if ($host === config('app.domains.account')) {
            return User::role('customer')->first();
        }

        return User::role('admin')->first();
    }
}
