<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\LeadConversionModel;
use App\Models\LeadModel;

class LeadConversionService
{
    protected LeadModel $leads;
    protected LeadConversionModel $conversions;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->leads       = new LeadModel();
        $this->conversions = new LeadConversionModel();
        $this->activity    = new ActivityLogModel();
    }

    public function convert(int $leadId, array $input, ?int $actingUserId): array
    {
        $lead = $this->leads->find($leadId);
        if (! $lead) {
            return ['success' => false, 'errors' => ['id' => 'Lead not found.']];
        }

        if ($lead['status'] === 'converted') {
            return ['success' => false, 'errors' => ['status' => 'This lead has already been converted.']];
        }

        $now = date('Y-m-d H:i:s');
        $conversionType = $input['conversion_type'] ?? 'customer';

        if (! $this->conversions->insert([
            'lead_id'         => $leadId,
            'converted_by'    => $actingUserId,
            'conversion_type' => $conversionType,
            'notes'           => $input['notes'] ?: null,
            'converted_at'    => $now,
            'created_at'      => $now,
        ], true)) {
            return ['success' => false, 'errors' => $this->conversions->errors()];
        }

        $this->leads->update($leadId, [
            'status'       => 'converted',
            'converted_at' => $now,
            'updated_by'   => $actingUserId,
        ]);

        $name = $this->leads->getFullName($lead);
        $this->activity->log(
            'lead_conversions',
            'converted',
            $actingUserId,
            "Converted lead #{$leadId} ({$name}) to {$conversionType}",
            (string) $leadId
        );

        return ['success' => true, 'id' => $this->conversions->getInsertID()];
    }
}
