<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/mvc.php';

use App\Middleware\AuthMiddleware;
use App\Services\AuthService;

function auth_service(): AuthService
{
    static $service = null;
    if ($service === null) {
        $service = new AuthService(\App\Services\ApiService::instance());
    }

    return $service;
}

function auth_middleware(): AuthMiddleware
{
    static $middleware = null;
    if ($middleware === null) {
        $middleware = new AuthMiddleware(auth_service());
    }

    return $middleware;
}

function auth_start(): void
{
    $config = app_config();
    if (session_status() === PHP_SESSION_NONE) {
        session_name($config['session_name']);

        $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || ((string)($_SERVER['SERVER_PORT'] ?? '') === '443')
            || (strtolower((string)($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '')) === 'https');

        $basePath = app_base_path();
        $cookiePath = $basePath !== '' ? $basePath . '/' : '/';

        session_set_cookie_params([
            'lifetime' => 0,
            'path' => $cookiePath,
            'secure' => $https,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);

        if (!@session_start()) {
            throw new RuntimeException('Could not start session. Check server session folder permissions.');
        }
    }
}

function auth_last_error(): string
{
    return auth_service()->lastError();
}

function auth_clear_last_error(): void
{
    auth_service()->clearError();
}

function auth_store_api_session(array $response): void
{
    auth_service()->storeUser(\App\Models\User::fromApiResponse($response), $response);
}

/** @return array<string,mixed>|null */
function auth_api_response(): ?array
{
    return auth_service()->apiResponse();
}

function auth_api_user(): ?array
{
    auth_start();
    $user = auth_service()->user();

    return $user?->toSessionArray();
}

function auth_api_token(): ?string
{
    return auth_service()->token();
}

function auth_login(string $email, string $password): bool
{
    auth_start();
    auth_clear_last_error();

    $email = trim($email);
    if ($email === '' || $password === '') {
        auth_service()->setError(__('login_error'));
        return false;
    }

    if (!api_auth_enabled()) {
        auth_service()->setError('Karvi Partner API authentication is not enabled.');
        return false;
    }

    $result = auth_service()->login($email, $password);

    return $result->success;
}

function auth_logout(): void
{
    auth_service()->logout();
}

function auth_check(): bool
{
    auth_start();

    return auth_service()->isAuthenticated();
}

function auth_require(): void
{
    auth_middleware()->requireAuth();
}
