<?php

namespace Modules\Procurement\Services;

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

class SupplierService
{
    protected SupplierModel $suppliers;
    protected ActivityLogModel $activity;

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

    public function create(array $input, ?int $actingUserId): array
    {
        $code = strtoupper(trim($input['code'] ?? ''));
        if ($code !== '' && $this->suppliers->isCodeTaken($code)) {
            return ['success' => false, 'errors' => ['code' => 'That supplier code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

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

        $id = $this->suppliers->getInsertID();
        $this->activity->log('suppliers', 'created', $actingUserId, "Created supplier #{$id} ({$data['name']})", (string) $id);

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

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

        $code = strtoupper(trim($input['code'] ?? ''));
        if ($code !== '' && $this->suppliers->isCodeTaken($code, $id)) {
            return ['success' => false, 'errors' => ['code' => 'That supplier code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code !== '' ? $code : null;
        $data['updated_by'] = $actingUserId;

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

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

        return ['success' => true];
    }

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

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

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'    => trim($input['name']),
            'email'   => trim($input['email'] ?? '') ?: null,
            'phone'   => trim($input['phone'] ?? '') ?: null,
            'website' => trim($input['website'] ?? '') ?: null,
            'address' => trim($input['address'] ?? '') ?: null,
            'city'    => trim($input['city'] ?? '') ?: null,
            'country' => trim($input['country'] ?? '') ?: null,
            'status'  => $input['status'] ?? 'active',
            'notes'   => $input['notes'] ?: null,
        ];
    }
}
