<?php
namespace Gestoreasy\Core\Admin;

use Gestoreasy\Core\Http\Request;
use Gestoreasy\Core\Http\Response;

class AdminAuthMiddleware {
    public static function requireAdminApi(): callable {
        return function (Request $req) {
            $auth = $req->header('authorization');
            if (!$auth || !str_starts_with($auth, 'Bearer ')) {
                return new Response(401, ['error' => 'Unauthorized']);
            }
            $jwt = substr($auth, 7);
            $payload = AdminJwt::verify($jwt);
            if (!$payload) {
                return new Response(401, ['error' => 'Invalid token']);
            }
            AdminUserContext::set($req, $payload);
            return null;
        };
    }
    public static function requireAdminHtml(): callable {
        return function (Request $req) {
            $cookieToken = $_COOKIE['admin_token'] ?? null;
            if (!$cookieToken) {
                return new Response(302, '', ['Location' => '/admin/login']);
            }
            $payload = AdminJwt::verify($cookieToken);
            if (!$payload) {
                return new Response(302, '', ['Location' => '/admin/login']);
            }
            AdminUserContext::set($req, $payload);
            return null;
        };
    }
}