<?php

namespace App\Filters;

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

/**
 * CodeIgniter 4.4.x doesn't ship a built-in CORS filter (that landed in
 * 4.5+) — this is a minimal equivalent so external API consumers (mobile
 * apps, third-party integrations per 07-api-documentation-structure.md)
 * can call /api/v1/* from a browser-based client on a different origin.
 * Allowed origins are configurable via .env; defaults to permissive '*'
 * for API routes only (never applied to the web/session-auth routes).
 */
class Cors implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if ($request->getMethod() === 'options') {
            $response = service('response');
            $this->applyHeaders($request, $response);
            return $response->setStatusCode(204);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        $this->applyHeaders($request, $response);
    }

    private function applyHeaders(RequestInterface $request, ResponseInterface $response): void
    {
        $allowedOrigins = env('cors.allowedOrigins') ?: '*';

        $response->setHeader('Access-Control-Allow-Origin', $allowedOrigins);
        $response->setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
        $response->setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
        $response->setHeader('Access-Control-Max-Age', '3600');
    }
}
