<?php

namespace App\Http\Controllers;

use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class MistakesFeedController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'team' => ['nullable', 'string', 'in:design,qa,misleads,bbs,mockupat'],
            'from_date' => ['nullable', 'date'],
            'to_date' => ['nullable', 'date'],
        ]);

        $baseUrl = trim((string) config('services.mistakes_feed.url', ''));

        if ($baseUrl === '') {
            return response()->json([
                'message' => 'The mistakes feed is not configured.',
            ], 503);
        }

        $team = $validated['team'] ?? 'design';
        $toDate = $validated['to_date'] ?? null;

        $sheetName = match ($team) {
            'qa' => 'QA_Data',
            'misleads' => 'Misleads',
            'bbs' => 'BBS',
            'mockupat' => 'MockupByLeads',
            default => 'Mistakes',
        };

        $query = [
            'sheet' => $sheetName,
        ];

        if (!empty($validated['from_date'])) {
            $query['start'] = $validated['from_date'];
        }

        if ($toDate) {
            $query['end'] = CarbonImmutable::parse($toDate)->addDay()->toDateString();
        }

        $response = Http::acceptJson()
            ->timeout((int) config('services.mistakes_feed.timeout', 30))
            ->get($baseUrl, $query);

        if (! $response->successful()) {
            return response()->json([
                'message' => 'Unable to load the mistakes feed.',
                'status' => $response->status(),
            ], 502);
        }

        $payload = $response->json();

        if (! is_array($payload)) {
            return response()->json([
                'message' => 'The mistakes feed returned an unexpected response.',
            ], 502);
        }

        return response()->json($payload);
    }
}
