<?php

namespace App\Services\ItemMaster;

use App\Models\ItemMaster\UnitOption;
use App\Services\Service;
use Illuminate\Database\Eloquent\Collection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class UnitOptionService extends Service
{
    /**
     * 단위 옵션 목록
     */
    public function index(): Collection
    {
        $tenantId = $this->tenantId();

        return UnitOption::where('tenant_id', $tenantId)
            ->orderBy('label')
            ->get();
    }

    /**
     * 단위 옵션 생성
     */
    public function store(array $data): UnitOption
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $unit = UnitOption::create([
            'tenant_id' => $tenantId,
            'label' => $data['label'],
            'value' => $data['value'],
            'created_by' => $userId,
        ]);

        return $unit;
    }

    /**
     * 단위 옵션 삭제
     */
    public function destroy(int $id): void
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $unit = UnitOption::where('tenant_id', $tenantId)
            ->where('id', $id)
            ->first();

        if (! $unit) {
            throw new NotFoundHttpException(__('error.not_found'));
        }

        $unit->update(['deleted_by' => $userId]);
        $unit->delete();
    }
}
