<?php

namespace App\Http\Middlewares;

use SelfPhp\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\models\ApiClient;
use SelfPhp\SPException;

class AuthApiMiddleware
{
    /**
     * Handle incoming API requests.
     *
     * @throws SPException
     */
    public function handle(Request $request)
    {
        try {   
            if (!$this->isAuthEnabled()) {
                throw new SPException('Authentication is disabled in environment configuration.', 503);
            }
            
            // Step 1: Validate client token
            $serverToken = $this->extractServerToken();
            if (!$serverToken || !$this->validateServerToken($serverToken)) {
                throw new SPException('Unauthorized server token.', 401);
            }
            
            return true;
        } catch (SPException $e) {
            throw new SPException($e->getMessage(), $e->getCode() ?: 401);
        } catch (\Exception $e) {
            throw new Exception('Server error: ' . $e->getMessage(), 500);
        }
    }

    protected function isAuthEnabled(): bool
    {
        return (bool) env('AUTH');
    }

    protected function extractServerToken(): ?string
    {
        $headers = getallheaders();
        return $headers['X-Server-Token'] ?? $headers['x-server-token'] ?? null;
    }

    protected function validateServerToken(string $token): bool
    {
        try {
            return ApiClient::validateServerToken($token);
        } catch (\Exception $e) {
            return false;
        }
    }
}