<?php

namespace App\Http\Controllers\Api\Leads;

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

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

        $leads = Lead::query()
            ->with(['stage', 'contact', 'assignee', 'pipeline'])
            ->where('tenant_id', $tenantId)
            ->orderByDesc('created_at')
            ->get()
            ->map(fn (Lead $lead) => [
                'id' => $lead->id,
                'title' => $lead->title,
                'stageId' => $lead->stage_id,
                'stageName' => $lead->stage?->name,
                'value' => $lead->estimated_value ? '$'.number_format((float) $lead->estimated_value, 2) : null,
                'valueNumeric' => $lead->estimated_value ? (float) $lead->estimated_value : null,
                'score' => $this->score($lead),
                'owner' => $lead->assignee?->full_name ?? 'Unassigned',
                'contactName' => $lead->contact?->primary_name,
                'status' => $lead->status,
            ])
            ->values();

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

    protected function score(Lead $lead): string
    {
        if (($lead->estimated_value ?? 0) >= 500) {
            return 'hot';
        }

        if (($lead->estimated_value ?? 0) >= 80) {
            return 'warm';
        }

        return 'cold';
    }
}
