<?php

declare(strict_types=1);

namespace WorkforceOS\Http;

use WorkforceOS\Services\AttendanceService;
use WorkforceOS\Services\AdminModuleService;
use WorkforceOS\Services\DashboardService;
use WorkforceOS\Services\DeviceService;
use WorkforceOS\Services\EmployeeService;
use WorkforceOS\Services\HrmModuleService;
use WorkforceOS\Services\OrganizationService;
use WorkforceOS\Services\PayrollService;
use WorkforceOS\Services\ReportService;
use WorkforceOS\Services\RuleService;
use WorkforceOS\Services\SaasOperationsService;
use WorkforceOS\Services\TenantRepository;

final class Router
{
    private TenantRepository $tenants;

    public function __construct()
    {
        $this->tenants = new TenantRepository();
    }

    public function dispatch(string $method, string $path): void
    {
        $this->applySecurityHeaders();

        if ($method === 'OPTIONS') {
            http_response_code(204);
            return;
        }

        if ($path === '/') {
            $this->servePortal();
            return;
        }

        if (!str_starts_with($path, '/api/')) {
            $this->json(['message' => 'Not found'], 404);
            return;
        }

        $body = $this->requestBody();
        $tenant = $this->tenants->resolve($_GET['tenant'] ?? 'acme-industries');
        $hrm = new HrmModuleService();
        $admin = new AdminModuleService();
        $organization = new OrganizationService();
        $saas = new SaasOperationsService();

        match ([$method, $path]) {
            ['GET', '/api/health'] => $this->json([
                'status' => 'ok',
                'service' => 'WorkforceOS API',
                'modules' => $this->tenants->enabledModules($tenant['id']),
            ]),
            ['GET', '/api/super-admin/dashboard'] => $this->json((new DashboardService())->superAdmin()),
            ['GET', '/api/clients'] => $this->json($admin->clients()),
            ['GET', '/api/packages'] => $this->json($admin->packages()),
            ['GET', '/api/billing'] => $this->json($saas->billing()),
            ['GET', '/api/monitoring'] => $this->json($saas->monitoring()),
            ['GET', '/api/registration-control'] => $this->json($saas->registrationControl()),
            ['GET', '/api/client/dashboard'] => $this->json((new DashboardService())->client($tenant)),
            ['GET', '/api/employees'] => $this->json((new EmployeeService())->list($tenant)),
            ['GET', '/api/transfers'] => $this->json($saas->transfers($tenant)),
            ['GET', '/api/organization'] => $this->json($organization->structure($tenant)),
            ['GET', '/api/schedules'] => $this->json($organization->schedules($tenant)),
            ['GET', '/api/attendance/today'] => $this->json((new AttendanceService())->today($tenant)),
            ['POST', '/api/attendance/logs'] => $this->json((new AttendanceService())->ingestLog($tenant, $body), 201),
            ['POST', '/api/payroll/preview'] => $this->json((new PayrollService())->preview($tenant, $body)),
            ['GET', '/api/devices'] => $this->json((new DeviceService())->list($tenant)),
            ['GET', '/api/rules'] => $this->json((new RuleService())->list($tenant)),
            ['GET', '/api/reports'] => $this->json((new ReportService())->catalogue($tenant)),
            ['GET', '/api/leaves'] => $this->json($hrm->leaves($tenant)),
            ['GET', '/api/holidays'] => $this->json($hrm->holidays($tenant)),
            ['GET', '/api/finance'] => $this->json($hrm->finance($tenant)),
            ['GET', '/api/tasks'] => $this->json($hrm->tasks($tenant)),
            ['GET', '/api/contracts'] => $this->json($hrm->contracts($tenant)),
            ['GET', '/api/disciplinary'] => $this->json($hrm->disciplinary($tenant)),
            ['GET', '/api/security'] => $this->json($hrm->security($tenant)),
            ['GET', '/api/settings'] => $this->json($hrm->settings($tenant)),
            default => $this->json(['message' => 'Endpoint not implemented yet', 'path' => $path], 404),
        };
    }

    private function servePortal(): void
    {
        header('Content-Type: text/html; charset=utf-8');
        readfile(__DIR__ . '/../../frontend/index.html');
    }

    private function requestBody(): array
    {
        $raw = file_get_contents('php://input') ?: '';
        if ($raw === '') {
            return [];
        }

        $decoded = json_decode($raw, true);
        return is_array($decoded) ? $decoded : [];
    }

    private function json(array $payload, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    }

    private function applySecurityHeaders(): void
    {
        header('Access-Control-Allow-Origin: http://127.0.0.1:5173');
        header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Tenant');
        header('X-Content-Type-Options: nosniff');
        header('X-Frame-Options: DENY');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
    }
}
