<?php

namespace App\Modules\Inventory\Services;

use App\Modules\Inventory\DTOs\WarehouseWriteData;
use App\Modules\Inventory\Models\Warehouse;
use App\Modules\Inventory\Repositories\WarehouseRepository;
use App\Modules\Inventory\Support\InventoryLifecycleState;
use App\Support\SystemReferenceAssigner;
use App\Support\SystemReferenceGenerator;

final class WarehouseManagementService
{
    public function __construct(
        private readonly WarehouseRepository $warehouses,
        private readonly SystemReferenceAssigner $references,
    ) {}

    public function store(WarehouseWriteData $data): Warehouse
    {
        $warehouse = $this->warehouses->create($this->tenantId(), [
            'code' => $this->references->pendingPlaceholder(SystemReferenceGenerator::WAREHOUSE),
            'name' => $data->name,
            'is_active' => true,
            'lifecycle_state' => InventoryLifecycleState::Active,
        ]);

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

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

        return (int) $id;
    }
}
