<?php

namespace Modules\Accounting\Services;

use App\Models\ActivityLogModel;
use App\Models\AssetCategoryModel;
use App\Models\FixedAssetModel;

class AssetCategoryService
{
    protected AssetCategoryModel $categories;
    protected FixedAssetModel $assets;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->categories = new AssetCategoryModel();
        $this->assets     = new FixedAssetModel();
        $this->activity   = new ActivityLogModel();
    }

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

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

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

        $id = (int) $this->categories->getInsertID();
        $this->activity->log('asset_categories', 'created', $actingUserId, "Created asset category #{$id} ({$data['code']})", (string) $id);

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

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

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

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

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

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

        return ['success' => true];
    }

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

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

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

        if ($this->assets->where('category_id', $id)->countAllResults() > 0) {
            return ['success' => false, 'error' => 'Cannot delete a category that has fixed assets.'];
        }

        $this->categories->delete($id);
        $this->activity->log('asset_categories', 'deleted', $actingUserId, "Deleted asset category #{$id}", (string) $id);

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        $account = static function ($key) use ($input): ?int {
            $id = (int) ($input[$key] ?? 0);

            return $id > 0 ? $id : null;
        };

        return [
            'name'                    => trim((string) $input['name']),
            'depreciation_method'     => $input['depreciation_method'] ?? 'straight_line',
            'useful_life_months'      => max(1, (int) ($input['useful_life_months'] ?? 60)),
            'salvage_percent'         => round((float) ($input['salvage_percent'] ?? 0), 2),
            'asset_account_id'        => $account('asset_account_id'),
            'accum_depr_account_id'   => $account('accum_depr_account_id'),
            'depr_expense_account_id' => $account('depr_expense_account_id'),
            'status'                  => $input['status'] ?? 'active',
            'notes'                   => ! empty($input['notes']) ? trim((string) $input['notes']) : null,
        ];
    }
}
