<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreLeadRequest;
use App\Models\LeadSource\LeadSourceEndpoint;
use App\Models\Solicitor\Solicitor;
use App\Services\ClientIntakeService;
use Illuminate\Http\JsonResponse;

class LeadIntakeController extends Controller
{
    public function store(
        StoreLeadRequest $request,
        string $key,
        ClientIntakeService $clientIntake
    ): JsonResponse {
        $endpoint = LeadSourceEndpoint::query()
            ->where('key', $key)
            ->where('status', 'active')
            ->firstOrFail();

        // The API route has no web tenant middleware (SetSolicitorFromDomain), so the
        // current Solicitor singleton is unbound here. Bind it from the endpoint before
        // creating the client: the ContactTriggerObserver fires MODEL_CREATED triggers
        // synchronously inside create(), and the dispatch pipeline resolves the email
        // sender + scopes trigger lookups via app(Solicitor::class). Without this, no
        // sender is found and the automatic email silently never queues. Mirrors the
        // explicit tenant rebind done by the contact queue jobs.
        app()->instance(Solicitor::class, $endpoint->solicitor);

        $client = $clientIntake->create([
            ...$request->validated(),
            'solicitor_id' => $endpoint->solicitor_id,
            'lead_source_id' => $endpoint->lead_source_id,
            'lead_source_endpoint_id' => $endpoint->id,
            'user_id' => $request->user()->id,
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Client and claim created successfully.',
            'data' => [
                'client_id' => $client->id,
                'claim_id' => $client->claim->id,
                'reference' => $client->reference,
            ],
        ], 201);
    }
}