<?php

namespace App\Http\Controllers\API\V1;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use Illuminate\Http\Request;
use App\Http\Requests\Lead\StoreLeadRequest;
use App\Http\Requests\Lead\UpdateLeadRequest;

class LeadController extends Controller
{
    /**
     * List leads
     */
    public function index(Request $request)
    {
        $leads = Lead::where('user_id', $request->user()->id)
            ->when($request->status, fn ($q) => $q->where('status', $request->status))
            ->orderBy('next_follow_up_at')
            ->paginate(20);

        return response()->json([
            'success' => true,
            'data' => $leads->items(),
            'meta' => [
                'total' => $leads->total(),
                'page'  => $leads->currentPage(),
            ],
            'error' => null,
        ]);
    }

    /**
     * Create lead
     */
    public function store(StoreLeadRequest $request)
    {
        $lead = $request->user()
            ->leads()
            ->create($request->validated());

        return response()->json([
            'success' => true,
            'data' => $lead,
            'error' => null,
        ], 201);
    }

    /**
     * View single lead
     */
    public function show(Lead $lead)
    {
        $this->authorize('view', $lead);

        $lead->load('followUps');

        return response()->json([
            'success' => true,
            'data' => $lead,
            'error' => null,
        ]);
    }

    /**
     * Update lead
     */
    public function update(UpdateLeadRequest $request, Lead $lead)
    {
        $this->authorize('update', $lead);

        $lead->update($request->validated());

        return response()->json([
            'success' => true,
            'data' => $lead,
            'error' => null,
        ]);
    }

    /**
     * Delete lead
     */
    public function destroy(Lead $lead)
    {
        $this->authorize('delete', $lead);

        $lead->delete();

        return response()->json([
            'success' => true,
            'data' => 'Lead deleted',
            'error' => null,
        ]);
    }
}
