<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Modules\Users\Models\Employee;

final class ApiAuthMiddleware
{
    public function handle(Request $request, callable $next): Response
    {
        $token = $request->bearerToken();
        if (!$token) {
            return (new Response())->json([
                'success' => false,
                'data' => null,
                'meta' => [],
                'errors' => ['Authentication required'],
            ], 401);
        }

        $db = App::getInstance()->db();
        $tokenRow = $db->selectOne(
            "SELECT employee_id, expires_at FROM api_tokens WHERE token = ? AND is_revoked = 0",
            [$token]
        );

        if (!$tokenRow) {
            return (new Response())->json([
                'success' => false,
                'data' => null,
                'meta' => [],
                'errors' => ['Invalid token'],
            ], 401);
        }

        if ($tokenRow['expires_at'] && $tokenRow['expires_at'] < date('Y-m-d H:i:s')) {
            return (new Response())->json([
                'success' => false,
                'data' => null,
                'meta' => [],
                'errors' => ['Token expired'],
            ], 401);
        }

        $employee = Employee::find((int) $tokenRow['employee_id']);
        if (!$employee || !$employee->is_active) {
            return (new Response())->json([
                'success' => false,
                'data' => null,
                'meta' => [],
                'errors' => ['Account inactive'],
            ], 401);
        }

        App::getInstance()->setCurrentEmployee($employee);

        $db->update('api_tokens', [
            'last_used_at' => date('Y-m-d H:i:s'),
        ], '`token` = ?', [$token]);

        return $next($request);
    }
}
