<?php

declare(strict_types=1);

namespace App\Application\Http\Controllers;

use App\Framework\Attributes\Route;
use App\Framework\Http\Headers;
use App\Framework\Http\HttpResponse;
use App\Framework\Http\Method;
use App\Framework\Http\Response;
use App\Framework\Http\Responses\JsonResponse;
use App\Framework\Http\Status;
use App\Framework\QrCode\ErrorCorrectionLevel;
use App\Framework\QrCode\QrCodeGenerator;
use App\Framework\QrCode\QrCodeVersion;

/**
 * QR Code API Controller
 *
 * Provides API endpoints for QR code generation using the Framework QrCode module
 */
final readonly class QrCodeController
{
    public function __construct(
        private QrCodeGenerator $qrCodeGenerator
    ) {
    }

    /**
     * Generate QR code as SVG
     */
    #[Route(path: '/api/qrcode/svg', method: Method::GET)]
    public function generateSvg(): Response
    {
        $data = $_GET['data'] ?? 'https://example.com';
        $errorLevel = $this->parseErrorLevel($_GET['error'] ?? 'M');
        $version = $_GET['version'] ?? null;

        try {
            $qrVersion = $version ? new QrCodeVersion((int) $version) : null;

            $svg = $this->qrCodeGenerator->generateSvg($data, $errorLevel, $qrVersion);

            return new HttpResponse(
                status : Status::OK,
                headers: new Headers(['Content-Type' => 'image/svg+xml']),
                body   : $svg
            );
        } catch (\Exception $e) {
            return new JsonResponse(
                body  : ['error' => $e->getMessage()],
                status: Status::BAD_REQUEST
            );
        }
    }

    /**
     * Generate QR code as Data URI (base64 encoded SVG)
     */
    #[Route(path: '/api/qrcode/datauri', method: Method::GET)]
    public function generateDataUri(): Response
    {
        $data = $_GET['data'] ?? 'https://example.com';
        $errorLevel = $this->parseErrorLevel($_GET['error'] ?? 'M');
        $version = $_GET['version'] ?? null;

        try {
            $qrVersion = $version ? new QrCodeVersion((int) $version) : null;

            $dataUri = $this->qrCodeGenerator->generateDataUri($data, $errorLevel, $qrVersion);

            return new JsonResponse(
                body   : ['dataUri' => $dataUri]
            );
        } catch (\Exception $e) {
            return new JsonResponse(
                body  : ['error' => $e->getMessage()],
                status: Status::BAD_REQUEST
            );
        }
    }

    /**
     * Analyze data and get QR code recommendations
     */
    #[Route(path: '/api/qrcode/analyze', method: Method::GET)]
    public function analyzeData(): Response
    {
        $data = $_GET['data'] ?? null;

        if (empty($data)) {
            return new JsonResponse(
                body  : ['error' => 'Data parameter is required'],
                status: Status::BAD_REQUEST
            );
        }

        try {
            $analysis = $this->qrCodeGenerator->analyzeData($data);

            return new JsonResponse(
                body  : $analysis,
                status: Status::OK
            );
        } catch (\Exception $e) {
            return new JsonResponse(
                body  : ['error' => $e->getMessage()],
                status: Status::BAD_REQUEST
            );
        }
    }

    /**
     * Generate TOTP QR code specifically optimized for authenticator apps
     */
    #[Route(path: '/api/qrcode/totp', method: Method::GET)]
    public function generateTotpQrCode(): HttpResponse
    {
        $totpUri = $_GET['uri'] ?? null;

        if (empty($totpUri)) {
            return new HttpResponse(
                status : Status::BAD_REQUEST,
                headers: new Headers(['Content-Type' => 'application/json']),
                body   : json_encode(['error' => 'TOTP URI parameter is required']) ?: '{"error":"Encoding failed"}'
            );
        }

        try {
            $svg = $this->qrCodeGenerator->generateTotpQrCode($totpUri);

            return new HttpResponse(
                status : Status::OK,
                headers: new Headers(['Content-Type' => 'image/svg+xml']),
                body   : $svg
            );
        } catch (\Exception $e) {
            return new HttpResponse(
                status : Status::BAD_REQUEST,
                headers: new Headers(['Content-Type' => 'application/json']),
                body   : json_encode(['error' => $e->getMessage()]) ?: '{"error":"Encoding failed"}'
            );
        }
    }

    /**
     * Parse error correction level from string
     */
    private function parseErrorLevel(string $level): ErrorCorrectionLevel
    {
        return match (strtoupper($level)) {
            'L' => ErrorCorrectionLevel::L,
            'Q' => ErrorCorrectionLevel::Q,
            'H' => ErrorCorrectionLevel::H,
            default => ErrorCorrectionLevel::M,
        };
    }
}
