<?php

namespace App\Services\Quote;

use App\Models\Quote\QuoteFormulaItem;
use Illuminate\Support\Collection;

class QuoteFormulaItemService
{
    /**
     * 수식별 품목 목록 조회
     */
    public function getItemsByFormula(int $formulaId): Collection
    {
        return QuoteFormulaItem::where('formula_id', $formulaId)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 품목 상세 조회
     */
    public function getItemById(int $id): ?QuoteFormulaItem
    {
        return QuoteFormulaItem::find($id);
    }

    /**
     * 품목 생성
     */
    public function createItem(int $formulaId, array $data): QuoteFormulaItem
    {
        // 순서 자동 설정
        if (! isset($data['sort_order'])) {
            $maxOrder = QuoteFormulaItem::where('formula_id', $formulaId)->max('sort_order') ?? 0;
            $data['sort_order'] = $maxOrder + 1;
        }

        return QuoteFormulaItem::create([
            'formula_id' => $formulaId,
            'item_code' => $data['item_code'],
            'item_name' => $data['item_name'],
            'specification' => $data['specification'] ?? null,
            'unit' => $data['unit'] ?? 'EA',
            'quantity_formula' => $data['quantity_formula'] ?? '1',
            'unit_price_formula' => $data['unit_price_formula'] ?? null,
            'sort_order' => $data['sort_order'],
        ]);
    }

    /**
     * 품목 수정
     */
    public function updateItem(int $itemId, array $data): QuoteFormulaItem
    {
        $item = QuoteFormulaItem::findOrFail($itemId);

        $item->update([
            'item_code' => $data['item_code'] ?? $item->item_code,
            'item_name' => $data['item_name'] ?? $item->item_name,
            'specification' => $data['specification'] ?? $item->specification,
            'unit' => $data['unit'] ?? $item->unit,
            'quantity_formula' => $data['quantity_formula'] ?? $item->quantity_formula,
            'unit_price_formula' => $data['unit_price_formula'] ?? $item->unit_price_formula,
        ]);

        return $item->fresh();
    }

    /**
     * 품목 삭제
     */
    public function deleteItem(int $itemId): void
    {
        QuoteFormulaItem::destroy($itemId);
    }

    /**
     * 순서 변경
     */
    public function reorder(array $itemIds): void
    {
        foreach ($itemIds as $order => $id) {
            QuoteFormulaItem::where('id', $id)->update(['sort_order' => $order + 1]);
        }
    }

    /**
     * 품목이 수식에 속하는지 확인
     */
    public function belongsToFormula(int $itemId, int $formulaId): bool
    {
        return QuoteFormulaItem::where('id', $itemId)
            ->where('formula_id', $formulaId)
            ->exists();
    }
}
