<?php

namespace Modules\Inventory\Services;

use App\Models\ActivityLogModel;
use App\Models\WarehouseModel;

class WarehouseService
{
    protected WarehouseModel $warehouses;
    protected ActivityLogModel $activity;

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

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

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

        if (! empty($data['is_default'])) {
            $this->clearDefault();
        }

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

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

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

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

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

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

        if (! empty($data['is_default'])) {
            $this->clearDefault($id);
        }

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

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

        return ['success' => true];
    }

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

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

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

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

        return ['success' => true];
    }

    protected function clearDefault(?int $exceptId = null): void
    {
        $builder = $this->warehouses->builder()->set('is_default', 0);
        if ($exceptId) {
            $builder->where('id !=', $exceptId);
        }
        $builder->update();
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'       => trim($input['name']),
            'address'    => trim($input['address'] ?? '') ?: null,
            'city'       => trim($input['city'] ?? '') ?: null,
            'country'    => trim($input['country'] ?? '') ?: null,
            'is_default' => ! empty($input['is_default']) ? 1 : 0,
            'status'     => $input['status'] ?? 'active',
            'notes'      => $input['notes'] ?: null,
        ];
    }
}
