<?php

declare(strict_types=1);

namespace App\Application\Api;

use App\Framework\Attributes\Route;
use App\Framework\Http\Method;
use App\Framework\Http\Request;
use App\Framework\Http\Session\CsrfProtection;
use App\Framework\Http\Session\FormIdGenerator;
use App\Framework\Router\Result\JsonResult;

final readonly class CsrfController
{
    public function __construct(
        private FormIdGenerator $formIdGenerator,
        private CsrfProtection $csrfProtection,
    ) {
    }

    #[Route('/api/csrf/token', Method::GET)]
    public function getToken(Request $request): JsonResult
    {
        $formAction = $request->query->get('action', '/');
        $formMethod = $request->query->get('method', 'post');

        $formId = $this->formIdGenerator->generateFormId($formAction, $formMethod);
        $token = $this->csrfProtection->generateToken($formId);

        // Generate honeypot data
        $honeypotData = $this->generateHoneypotData();

        return new JsonResult([
            'form_id' => $formId,
            'token' => $token->toString(),
            'honeypot' => $honeypotData,
            'headers' => [
                'X-CSRF-Form-ID' => $formId,
                'X-CSRF-Token' => $token->toString(),
            ],
        ]);
    }

    #[Route('/api/csrf/token', Method::POST)]
    public function getTokenForForm(Request $request): JsonResult
    {
        $data = $request->parsedBody;
        $formAction = $data->get('action', '/');
        $formMethod = $data->get('method', 'post');

        $formId = $this->formIdGenerator->generateFormId($formAction, $formMethod);
        $token = $this->csrfProtection->generateToken($formId);

        // Generate honeypot data
        $honeypotData = $this->generateHoneypotData();

        return new JsonResult([
            'form_id' => $formId,
            'token' => $token->toString(),
            'honeypot' => $honeypotData,
            'headers' => [
                'X-CSRF-Form-ID' => $formId,
                'X-CSRF-Token' => $token->toString(),
            ],
        ]);
    }

    private function generateHoneypotData(): array
    {
        $honeypotNames = [
            'email_confirm',
            'website_url',
            'phone_number',
            'user_name',
            'company_name',
        ];

        $honeypotName = $honeypotNames[array_rand($honeypotNames)];

        return [
            'name' => $honeypotName,
            'value' => '', // Must be empty to pass validation
            'fields' => [
                '_honeypot_name' => $honeypotName,
                $honeypotName => '',
                '_form_start_time' => (string) time(), // Current timestamp for time validation
            ],
        ];
    }
}
