<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\PipelineStage;
use App\Services\LeadService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LeadStageController extends Controller
{
    public function update(Request $request, Lead $lead, LeadService $leadService): JsonResponse
    {
        $this->authorize('update', $lead);

        $data = $request->validate([
            'pipeline_stage_id' => ['required', 'integer', 'exists:pipeline_stages,id'],
        ]);

        $stage = PipelineStage::where('id', $data['pipeline_stage_id'])
            ->where('company_id', $lead->company_id)
            ->firstOrFail();

        $leadService->moveToStage($lead, $stage, $request->user());

        return response()->json(['ok' => true]);
    }
}
