<?php

declare(strict_types=1);

namespace App\Controller;

use App\Commerce\CommerceReferenceStore;
use App\Context\ContextService;
use App\Http\ClientIdResolver;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * HistoryController
 *
 * Read-only and destructive endpoints for conversation history.
 *
 * Responsibilities:
 * - Expose stored chat history for frontend reload
 * - Allow explicit deletion of the current client's history
 *
 * Identity handling:
 * - Client identity is resolved exclusively via ClientIdResolver
 * - No user identifiers are accepted from the request
 */
final readonly class HistoryController
{
    public function __construct(
        private ContextService $contextService,
        private ClientIdResolver $clientIdResolver,
        private CommerceReferenceStore $commerceReferenceStore,
    ) {
    }

    /**
     * Returns the full conversation history for the current client
     * in a frontend-friendly structure.
     */
    #[Route('/history', name: 'chat_history', methods: ['GET'])]
    public function history(Request $request): JsonResponse
    {
        // Resolve client ID (cookie-based)
        $response = new Response();
        $clientId = $this->clientIdResolver->resolve($request, $response);

        $raw = $this->contextService->buildUserContext($clientId, full: true);

        if ($raw === '') {
            return $this->jsonWithCookies([], $response);
        }

        $messages = [];
        $lines = explode("\n", $raw);

        $assistantBuffer = [];

        foreach ($lines as $line) {
            // User message
            if (str_starts_with($line, 'Question: ')) {
                // Flush previous assistant output
                if ($assistantBuffer !== []) {
                    $messages[] = [
                        'role' => 'assistant',
                        'text' => trim(implode("\n", $assistantBuffer)),
                    ];
                    $assistantBuffer = [];
                }

                $messages[] = [
                    'role' => 'user',
                    'text' => trim(substr($line, 10)),
                ];

                continue;
            }

            // Assistant output (can span multiple lines)
            if (trim($line) !== '') {
                $assistantBuffer[] = $line;
            }
        }

        // Flush trailing assistant output
        if ($assistantBuffer !== []) {
            $messages[] = [
                'role' => 'assistant',
                'text' => trim(implode("\n", $assistantBuffer)),
            ];
        }

        return $this->jsonWithCookies($messages, $response);
    }

    /**
     * Deletes the complete conversation history for the current client.
     */
    #[Route('/history/delete', name: 'delete_history', methods: ['POST'])]
    public function delete(Request $request): JsonResponse
    {
        // Resolve client ID (cookie-based)
        $response = new Response();
        $clientId = $this->clientIdResolver->resolve($request, $response);

        $this->contextService->deleteHistory($clientId);
        $this->commerceReferenceStore->clear($clientId);

        return $this->jsonWithCookies(
            [
                'status' => 'ok',
                'message' => 'History deleted',
            ],
            $response
        );
    }

    /**
     * Helper to return JSON responses while forwarding cookies.
     *
     * @param array<string, mixed>|array<int, array<string, string>> $data
     */
    private function jsonWithCookies(array $data, Response $cookieResponse): JsonResponse
    {
        $json = new JsonResponse($data);

        foreach ($cookieResponse->headers->getCookies() as $cookie) {
            $json->headers->setCookie($cookie);
        }

        return $json;
    }
}