<?php

declare(strict_types=1);

namespace App\Middlewares;

use App\Helpers\Request;

class CorsMiddleware
{
    public function handle(Request $request): mixed
    {
        $allowedOrigins = [
            $_ENV['APP_URL'] ?? 'http://localhost:8000',
            'http://localhost:5173',
            'http://localhost:5174',
            'http://localhost:4173',
            'https://italvettools.com',
            'https://app.italvettools.com',
            'https://www.italvettools.com',
        ];

        $origin = $_SERVER['HTTP_ORIGIN'] ?? '';

        if (in_array($origin, $allowedOrigins)) {
            header('Access-Control-Allow-Origin: ' . $origin);
            header('Access-Control-Allow-Credentials: true');
        } else {
            header('Access-Control-Allow-Origin: ' . $allowedOrigins[0]);
        }

        header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
        header('Access-Control-Max-Age: 86400');
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('X-Robots-Tag: noindex, nofollow');

        if ($request->method() === 'OPTIONS') {
            http_response_code(200);
            exit;
        }

        return null;
    }
}
