<?php

namespace App\Modules\Inventory\Services;

use App\Modules\Inventory\DTOs\InventoryAttributeWriteData;
use App\Modules\Inventory\Models\InventoryAttribute;
use App\Modules\Inventory\Repositories\InventoryAttributeRepository;
use App\Modules\Inventory\Support\InventoryAttributeType;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

final class InventoryAttributeManagementService
{
    public function __construct(
        private readonly InventoryAttributeRepository $attributes,
    ) {}

    /**
     * @return array<string, string>
     */
    public function typeSelectOptions(): array
    {
        $options = [];
        foreach (InventoryAttributeType::cases() as $case) {
            $options[$case->value] = __('inventory.attributes.types.'.$case->value);
        }

        return $options;
    }

    public function store(InventoryAttributeWriteData $data): InventoryAttribute
    {
        if ($data->requiresOptions() && $data->options === []) {
            throw ValidationException::withMessages([
                'options' => [__('inventory.attributes.validation.options_required')],
            ]);
        }

        return DB::transaction(function () use ($data): InventoryAttribute {
            $attribute = $this->attributes->create($this->tenantId(), [
                'code' => $data->code,
                'name' => $data->name,
                'type' => $data->type->value,
                'is_active' => true,
            ]);

            foreach ($data->options as $index => $option) {
                $attribute->options()->create([
                    'value_key' => $option['value_key'],
                    'label' => $option['label'],
                    'sort_order' => $index,
                ]);
            }

            return $attribute;
        });
    }

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

        return (int) $id;
    }
}
