<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\Admin;

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

final class DiscoveryFeedbackReportController extends Controller
{
    public function __construct(private readonly DiscoveryFeedbackReportService $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'] ?? 20);

        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(),
            ],
            'overview' => $report['overview'],
            'daily_feedback' => $report['daily_feedback'],
            'trend_summary' => $report['trend_summary'],
            'by_surface' => $report['by_surface'],
            'by_algo_surface' => $report['by_algo_surface'],
            'top_artworks' => $report['top_artworks'],
            'latest_aggregated_date' => $report['latest_aggregated_date'],
        ], Response::HTTP_OK);
    }
}
