<?php

namespace Modules\Procurement\Services;

use App\Models\ActivityLogModel;
use App\Models\SupplierContractModel;
use App\Models\SupplierModel;

class SupplierContractService
{
    protected SupplierContractModel $contracts;
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->contracts = new SupplierContractModel();
        $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['number']     = $this->contracts->nextNumber();
        $data['status']     = in_array($input['status'] ?? 'draft', ['draft', 'active'], true)
            ? ($input['status'] ?? 'draft')
            : 'draft';
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

        $id = (int) $this->contracts->getInsertID();
        $this->activity->log('supplier_contracts', 'created', $actingUserId, "Created supplier contract #{$id} ({$data['number']})", (string) $id);

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

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return ['success' => false, 'errors' => ['id' => 'Supplier contract not found.']];
        }
        if (in_array($contract['status'], ['terminated', 'cancelled'], true)) {
            return ['success' => false, 'errors' => ['status' => 'Terminated or cancelled contracts cannot be edited.']];
        }

        $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['updated_by'] = $actingUserId;

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

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

        return ['success' => true];
    }

    public function activate(int $id, ?int $actingUserId): array
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return ['success' => false, 'error' => 'Supplier contract not found.'];
        }
        if ($contract['status'] !== 'draft') {
            return ['success' => false, 'error' => 'Only draft contracts can be activated.'];
        }

        $this->contracts->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('supplier_contracts', 'activated', $actingUserId, "Activated supplier contract #{$id}", (string) $id);

        return ['success' => true];
    }

    public function terminate(int $id, ?int $actingUserId): array
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return ['success' => false, 'error' => 'Supplier contract not found.'];
        }
        if ($contract['status'] !== 'active') {
            return ['success' => false, 'error' => 'Only active contracts can be terminated.'];
        }

        $this->contracts->update($id, ['status' => 'terminated', 'updated_by' => $actingUserId]);
        $this->activity->log('supplier_contracts', 'terminated', $actingUserId, "Terminated supplier contract #{$id}", (string) $id);

        return ['success' => true];
    }

    public function cancel(int $id, ?int $actingUserId): array
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return ['success' => false, 'error' => 'Supplier contract not found.'];
        }
        if (! in_array($contract['status'], ['draft', 'active'], true)) {
            return ['success' => false, 'error' => 'Only draft or active contracts can be cancelled.'];
        }

        $this->contracts->update($id, ['status' => 'cancelled', 'updated_by' => $actingUserId]);
        $this->activity->log('supplier_contracts', 'cancelled', $actingUserId, "Cancelled supplier contract #{$id}", (string) $id);

        return ['success' => true];
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $contract = $this->contracts->find($id);
        if (! $contract) {
            return ['success' => false, 'error' => 'Supplier contract not found.'];
        }
        if (! in_array($contract['status'], ['draft', 'cancelled'], true)) {
            return ['success' => false, 'error' => 'Only draft or cancelled contracts can be deleted.'];
        }

        $this->contracts->delete($id);
        $this->activity->log('supplier_contracts', 'deleted', $actingUserId, "Deleted supplier contract #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'title'       => trim((string) ($input['title'] ?? '')),
            'supplier_id' => (int) $input['supplier_id'],
            'start_date'  => ! empty($input['start_date']) ? $input['start_date'] : null,
            'end_date'    => ! empty($input['end_date']) ? $input['end_date'] : null,
            'value'       => (float) ($input['value'] ?? 0),
            'notes'       => trim((string) ($input['notes'] ?? '')) ?: null,
        ];
    }
}
