<?php

namespace App\Http\Controllers;

use App\Services\ApiResponseCache;
use App\Models\UserMistake;
use App\Support\RosterData;
use Carbon\CarbonImmutable;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class UserMistakeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'team' => ['nullable', 'string', 'in:qa,designers,all'],
            'user_name' => ['nullable', 'string', 'max:255'],
            'from_date' => ['nullable', 'date'],
            'to_date' => ['nullable', 'date'],
            'page' => ['nullable', 'integer', 'min:1'],
            'per_page' => ['nullable', 'integer', 'min:1', 'max:200'],
        ]);

        $team = RosterData::normalizeTeam($validated['team'] ?? 'all', 'all');
        $perPage = min(max((int) ($validated['per_page'] ?? 20), 1), 200);
        $userName = trim((string) ($validated['user_name'] ?? ''));

        $query = UserMistake::query()
            ->when($team !== 'all', fn ($builder) => $builder->where('team', $team))
            ->when($userName !== '', fn ($builder) => $builder->where('user_name', $userName));

        $fromDate = $validated['from_date'] ?? null;
        $toDate = $validated['to_date'] ?? null;

        if ($fromDate && $toDate) {
            $from = CarbonImmutable::parse($fromDate)->startOfDay();
            $to = CarbonImmutable::parse($toDate)->endOfDay();

            if ($from->greaterThan($to)) {
                [$from, $to] = [$to, $from];
            }

            $query->whereBetween('issue_date', [$from->toDateTimeString(), $to->toDateTimeString()]);
        }

        $totalAmount = (clone $query)->sum('amount');

        $paginator = $query
            ->latest('issue_date')
            ->latest('id')
            ->paginate($perPage);

        return response()->json(array_merge($paginator->toArray(), [
            'total_amount' => round((float) $totalAmount, 2),
        ]));
    }

    public function store(Request $request, ApiResponseCache $apiResponseCache): JsonResponse
    {
        $validated = $request->validate([
            'user_name' => ['required', 'string', 'max:255'],
            'team' => ['required', 'string', 'in:qa,designers'],
            'issue_type' => ['nullable', 'string', 'max:120'],
            'customer_name' => ['nullable', 'string', 'max:255'],
            'project_name' => ['nullable', 'string', 'max:255'],
            'issue_date' => ['nullable', 'date'],
            'status' => ['nullable', 'string', 'max:120'],
            'notes' => ['nullable', 'string'],
            'amount' => ['nullable', 'numeric', 'min:0'],
            'record_external_id' => ['nullable', 'string', 'max:255'],
        ]);

        $mistake = UserMistake::query()->create([
            'user_name' => $validated['user_name'],
            'team' => RosterData::normalizeTeam($validated['team']),
            'issue_type' => $validated['issue_type'] ?? null,
            'customer_name' => $validated['customer_name'] ?? null,
            'project_name' => $validated['project_name'] ?? null,
            'issue_date' => $validated['issue_date'] ?? null,
            'status' => $validated['status'] ?? null,
            'notes' => $validated['notes'] ?? null,
            'amount' => round((float) ($validated['amount'] ?? 0), 2),
            'record_external_id' => $validated['record_external_id'] ?? null,
        ]);
        $apiResponseCache->invalidateGroups(['user_mistakes']);

        return response()->json($mistake, 201);
    }
}
