<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class CorsFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null): mixed
    {
        // Stamp CORS headers onto the singleton now so they survive any early return
        // (e.g. 401 from AuthFilter) — setHeader() does not clear other headers.
        $resp = service('response');
        $resp->setHeader('Access-Control-Allow-Origin', '*')
             ->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
             ->setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept');

        if (strtoupper($request->getMethod()) === 'OPTIONS') {
            return $resp->setStatusCode(200)
                        ->setContentType('application/json')
                        ->setBody('')
                        ->setHeader('Access-Control-Max-Age', '86400');
        }

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): ResponseInterface
    {
        return $response
            ->setHeader('Access-Control-Allow-Origin', '*')
            ->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
            ->setHeader('Access-Control-Allow-Headers', 'Authorization, Content-Type, Accept');
    }
}
