<?php

namespace App\Services;

use App\Models\Customer;
use App\Models\CustomerActivity;
use App\Models\Lead;
use App\Models\PipelineStage;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class CustomerService
{
    public function __construct(
        private LeadService $leadService
    ) {}

    public function convertFromLead(Lead $lead, ?User $actor = null, ?float $lifetimeValue = null): Customer
    {
        return DB::transaction(function () use ($lead, $actor, $lifetimeValue) {
            if ($lead->customer) {
                return $lead->customer;
            }

            $convertedStage = PipelineStage::withoutGlobalScope('company')
                ->where('company_id', $lead->company_id)
                ->where('name', 'Converted')
                ->first();

            if ($convertedStage) {
                $lead->update(['pipeline_stage_id' => $convertedStage->id]);
                $this->leadService->logActivity(
                    $lead,
                    'stage_change',
                    'Moved to Converted.',
                    ['to_stage_id' => $convertedStage->id],
                    $actor
                );
            }

            $customer = Customer::create([
                'company_id' => $lead->company_id,
                'lead_id' => $lead->id,
                'name' => $lead->name,
                'phone' => $lead->phone,
                'email' => $lead->email,
                'notes' => $lead->notes,
                'lifetime_value' => $lifetimeValue,
            ]);

            $this->leadService->logActivity(
                $lead,
                'converted',
                'Converted to customer #'.$customer->id,
                ['customer_id' => $customer->id],
                $actor
            );

            CustomerActivity::create([
                'company_id' => $customer->company_id,
                'customer_id' => $customer->id,
                'user_id' => $actor?->id,
                'type' => 'created',
                'description' => 'Customer created from lead #'.$lead->id,
                'meta' => ['lead_id' => $lead->id],
            ]);

            return $customer;
        });
    }
}
