<?php

namespace App\Filters;

use App\Libraries\JwtAuth;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Ensures API requests have a valid JWT Bearer token and user is active (jambo_status).
 * Returns 401 JSON when unauthorized or when user is deactivated.
 */
class ApiAuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        $path = $request->getUri()->getPath();
        if (str_contains($path, 'auth/login') || str_contains($path, 'auth/register') || str_contains($path, 'version')) {
            return null;
        }

        $token = $request->getHeaderLine('Authorization');
        $payload = JwtAuth::decode($token);
        if ($payload === null) {
            return $this->unauthorized();
        }

        $userId = (int) $payload->sub;
        $db = \Config\Database::connect();
        $row = $db->table('users')->where('id', $userId)->get()->getRow();
        if (! $row) {
            return $this->unauthorized();
        }
        if ($row->jambo_status === 'inactive') {
            return $this->unauthorized('Account deactivated');
        }

        JwtAuth::setCurrentUser((object) [
            'id'    => (int) $row->id,
            'phone' => $row->phone,
            'role'  => $row->role ?? 'user',
        ]);

        return null;
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        return $response;
    }

    private function unauthorized(string $message = 'Unauthorized'): ResponseInterface
    {
        return service('response')
            ->setStatusCode(401)
            ->setJSON([
                'data'  => null,
                'error' => [
                    'code'    => '401',
                    'message' => $message,
                ],
            ])
            ->setHeader('Content-Type', 'application/json');
    }
}
