<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\LeadAssignmentRuleModel;
use App\Models\LeadModel;

class LeadAssignmentService
{
    protected LeadAssignmentRuleModel $rules;
    protected LeadModel $leads;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $data = $this->mapInput($input, $actingUserId);
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

        if (! $this->rules->insert($data, true)) {
            return ['success' => false, 'errors' => $this->rules->errors()];
        }

        $id = $this->rules->getInsertID();
        $this->activity->log('lead_assignment_rules', 'created', $actingUserId, "Created lead assignment rule #{$id}", (string) $id);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $rule = $this->rules->find($id);
        if (! $rule) {
            return ['success' => false, 'errors' => ['id' => 'Assignment rule not found.']];
        }

        $data = $this->mapInput($input, $actingUserId);
        $data['updated_by'] = $actingUserId;

        if (! $this->rules->update($id, $data)) {
            return ['success' => false, 'errors' => $this->rules->errors()];
        }

        $this->activity->log('lead_assignment_rules', 'updated', $actingUserId, "Updated lead assignment rule #{$id}", (string) $id);

        return ['success' => true];
    }

    public function activate(int $id, ?int $actingUserId): void
    {
        $this->rules->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('lead_assignment_rules', 'activated', $actingUserId, "Activated assignment rule #{$id}", (string) $id);
    }

    public function deactivate(int $id, ?int $actingUserId): void
    {
        $this->rules->update($id, ['status' => 'inactive', 'updated_by' => $actingUserId]);
        $this->activity->log('lead_assignment_rules', 'deactivated', $actingUserId, "Deactivated assignment rule #{$id}", (string) $id);
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $rule = $this->rules->find($id);
        if (! $rule) {
            return ['success' => false, 'error' => 'Assignment rule not found.'];
        }

        $this->rules->delete($id);
        $this->activity->log('lead_assignment_rules', 'deleted', $actingUserId, "Deleted assignment rule #{$id}", (string) $id);

        return ['success' => true];
    }

    public function resolveAssignee(?int $leadSourceId): ?int
    {
        foreach ($this->rules->getActiveOrdered() as $rule) {
            if ($rule['lead_source_id'] === null || (int) $rule['lead_source_id'] === (int) $leadSourceId) {
                return (int) $rule['assign_to_user_id'];
            }
        }

        return null;
    }

    public function assignUnassigned(?int $actingUserId): int
    {
        $assigned = 0;

        foreach ($this->leads->getUnassigned() as $lead) {
            $userId = $this->resolveAssignee($lead['lead_source_id'] ? (int) $lead['lead_source_id'] : null);
            if ($userId) {
                $this->leads->update($lead['id'], [
                    'assigned_to' => $userId,
                    'updated_by'  => $actingUserId,
                ]);
                $assigned++;
            }
        }

        if ($assigned > 0) {
            $this->activity->log('lead_assignment_rules', 'bulk_assign', $actingUserId, "Auto-assigned {$assigned} unassigned lead(s)");
        }

        return $assigned;
    }

    protected function mapInput(array $input, ?int $actingUserId): array
    {
        return [
            'name'              => trim($input['name']),
            'lead_source_id'    => ! empty($input['lead_source_id']) ? (int) $input['lead_source_id'] : null,
            'assign_to_user_id' => (int) $input['assign_to_user_id'],
            'priority'          => (int) ($input['priority'] ?? 0),
            'status'            => $input['status'] ?? 'active',
        ];
    }
}
