<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Services\Analytics\TagInteractionReportService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

final class TagInteractionReportController extends Controller
{
    public function __construct(private readonly TagInteractionReportService $reportService) {}

    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'from' => ['nullable', 'date_format:Y-m-d'],
            'to' => ['nullable', 'date_format:Y-m-d'],
            'limit' => ['nullable', 'integer', 'min:1', 'max:100'],
        ]);

        $from = (string) ($validated['from'] ?? now()->subDays(13)->toDateString());
        $to = (string) ($validated['to'] ?? now()->toDateString());
        $limit = (int) ($validated['limit'] ?? 15);

        if ($from > $to) {
            return response()->json([
                'message' => 'Invalid date range: from must be before or equal to to.',
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $report = $this->reportService->buildReport($from, $to, $limit);

        return response()->json([
            'meta' => [
                'from' => $from,
                'to' => $to,
                'limit' => $limit,
                'generated_at' => now()->toISOString(),
                'latest_aggregated_date' => $report['latest_aggregated_date'],
            ],
            'overview' => $report['overview'],
            'daily_clicks' => $report['daily_clicks'],
            'by_surface' => $report['by_surface'],
            'top_tags' => $report['top_tags'],
            'top_queries' => $report['top_queries'],
            'top_transitions' => $report['top_transitions'],
        ], Response::HTTP_OK);
    }
}
