<?php

namespace App\Http\Controllers\Api\Reports;

use App\Domains\Leads\Models\Lead;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class LostReasonsReportController extends Controller
{
    public function __invoke(): JsonResponse
    {
        $tenantId = request()->user()->tenant_id;

        $rows = Lead::query()
            ->with('lostReason')
            ->where('tenant_id', $tenantId)
            ->whereNotNull('lost_reason_id')
            ->get()
            ->groupBy(fn (Lead $lead) => $lead->lostReason?->name ?? 'Unknown')
            ->map(fn ($group, $reason) => [
                'reason' => $reason,
                'count' => $group->count(),
            ])
            ->values();

        return response()->json(['data' => $rows]);
    }
}
