<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\SupplierContactModel;
use App\Models\SupplierModel;

class SupplierContactService
{
    protected SupplierContactModel $contacts;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->contacts  = new SupplierContactModel();
        $this->suppliers = new SupplierModel();
        $this->activity  = new ActivityLogModel();
    }

    public function create(array $input, ?int $actingUserId): array
    {
        $supplierId = (int) ($input['supplier_id'] ?? 0);
        if (! $this->suppliers->find($supplierId)) {
            return ['success' => false, 'errors' => ['supplier_id' => 'Supplier not found.']];
        }

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

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

        $id = $this->contacts->getInsertID();
        if (! empty($data['is_primary'])) {
            $this->clearOtherPrimaries($supplierId, $id);
        }

        $name = $this->contacts->getFullName($data);
        $this->activity->log('supplier_contacts', 'created', $actingUserId, "Created supplier contact #{$id} ({$name})", (string) $id);

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

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

        $supplierId = (int) ($input['supplier_id'] ?? $contact['supplier_id']);
        if (! $this->suppliers->find($supplierId)) {
            return ['success' => false, 'errors' => ['supplier_id' => 'Supplier not found.']];
        }

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

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

        if (! empty($data['is_primary'])) {
            $this->clearOtherPrimaries($supplierId, $id);
        }

        $this->activity->log('supplier_contacts', 'updated', $actingUserId, "Updated supplier contact #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

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

        $this->contacts->delete($id);
        $this->activity->log('supplier_contacts', 'deleted', $actingUserId, "Deleted supplier contact #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function clearOtherPrimaries(int $supplierId, int $keepId): void
    {
        $this->contacts->builder()
            ->where('supplier_id', $supplierId)
            ->where('id !=', $keepId)
            ->update(['is_primary' => 0]);
    }

    protected function mapInput(array $input): array
    {
        return [
            'supplier_id' => (int) $input['supplier_id'],
            'first_name'  => trim($input['first_name']),
            'last_name'   => trim($input['last_name']),
            'email'       => trim($input['email'] ?? '') ?: null,
            'phone'       => trim($input['phone'] ?? '') ?: null,
            'job_title'   => trim($input['job_title'] ?? '') ?: null,
            'is_primary'  => ! empty($input['is_primary']) ? 1 : 0,
            'status'      => $input['status'] ?? 'active',
            'notes'       => $input['notes'] ?: null,
        ];
    }
}
