<?php

namespace App\Modules\Inventory\Services;

use App\Modules\Inventory\DTOs\ItemCategoryWriteData;
use App\Modules\Inventory\Models\ItemCategory;
use App\Modules\Inventory\Repositories\ItemCategoryRepository;
use App\Support\SystemReferenceAssigner;
use App\Support\SystemReferenceGenerator;

final class ItemCategoryManagementService
{
    public function __construct(
        private readonly ItemCategoryRepository $categories,
        private readonly SystemReferenceAssigner $references,
    ) {}

    /**
     * @return array<int, string>
     */
    public function parentSelectOptions(): array
    {
        return $this->categories->parentSelectOptions();
    }

    public function store(ItemCategoryWriteData $data): ItemCategory
    {
        $category = $this->categories->create($this->tenantId(), [
            'code' => $this->references->pendingPlaceholder(SystemReferenceGenerator::CATEGORY),
            'name' => $data->name,
            'parent_id' => $data->parentId,
            'sort_order' => $data->sortOrder,
            'is_active' => true,
        ]);

        return $this->references->assign($category, SystemReferenceGenerator::CATEGORY, 'code');
    }

    private function tenantId(): int
    {
        $id = auth()->user()?->tenant_id;
        if ($id === null) {
            abort(403);
        }

        return (int) $id;
    }
}
