<?php
declare(strict_types=1);

namespace App\Middleware;

use App\Core\Request;
use App\Core\Response;
use App\Core\App;

final class CoachApiAuthMiddleware
{
    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 coach_id, expires_at FROM coach_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);
        }

        $coach = $db->selectOne(
            "SELECT * FROM coaches WHERE id = ? AND is_archived = 0",
            [(int) $tokenRow['coach_id']]
        );

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

        App::getInstance()->setCurrentCoach((object) $coach);

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

        return $next($request);
    }
}
