<?php

namespace App\Modules\Inventory\Services;

use App\Modules\Inventory\DTOs\ItemWriteData;
use App\Modules\Inventory\Models\Item;
use App\Modules\Inventory\Repositories\ItemRepository;
use App\Modules\Inventory\Support\InventoryLifecycleState;
use App\Support\SystemReferenceAssigner;
use App\Support\SystemReferenceGenerator;

final class ItemManagementService
{
    public function __construct(
        private readonly ItemRepository $items,
        private readonly SystemReferenceAssigner $references,
    ) {}

    public function store(ItemWriteData $data): Item
    {
        $item = $this->items->create($this->tenantId(), [
            'sku' => $this->references->pendingPlaceholder(SystemReferenceGenerator::ITEM),
            'name' => $data->name,
            'inventory_category_id' => $data->inventoryCategoryId,
            'barcode' => $data->barcode !== '' ? $data->barcode : null,
            'description' => $data->description !== '' ? $data->description : null,
            'is_variant' => false,
            'is_active' => true,
            'lifecycle_state' => InventoryLifecycleState::Active,
        ]);

        return $this->references->assign($item, SystemReferenceGenerator::ITEM, 'sku');
    }

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

        return (int) $id;
    }
}
