<?php

namespace App\Services\Quote;

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

class QuoteFormulaRangeService
{
    /**
     * 수식별 범위 목록 조회
     */
    public function getRangesByFormula(int $formulaId): Collection
    {
        return QuoteFormulaRange::where('formula_id', $formulaId)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 범위 상세 조회
     */
    public function getRangeById(int $id): ?QuoteFormulaRange
    {
        return QuoteFormulaRange::find($id);
    }

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

        return QuoteFormulaRange::create([
            'formula_id' => $formulaId,
            'min_value' => $data['min_value'] ?? null,
            'max_value' => $data['max_value'] ?? null,
            'condition_variable' => $data['condition_variable'],
            'result_value' => $data['result_value'],
            'result_type' => $data['result_type'] ?? 'fixed',
            'sort_order' => $data['sort_order'],
        ]);
    }

    /**
     * 범위 수정
     */
    public function updateRange(int $rangeId, array $data): QuoteFormulaRange
    {
        $range = QuoteFormulaRange::findOrFail($rangeId);

        $range->update([
            'min_value' => array_key_exists('min_value', $data) ? $data['min_value'] : $range->min_value,
            'max_value' => array_key_exists('max_value', $data) ? $data['max_value'] : $range->max_value,
            'condition_variable' => $data['condition_variable'] ?? $range->condition_variable,
            'result_value' => $data['result_value'] ?? $range->result_value,
            'result_type' => $data['result_type'] ?? $range->result_type,
        ]);

        return $range->fresh();
    }

    /**
     * 범위 삭제
     */
    public function deleteRange(int $rangeId): void
    {
        QuoteFormulaRange::destroy($rangeId);
    }

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

    /**
     * 범위가 수식에 속하는지 확인
     */
    public function belongsToFormula(int $rangeId, int $formulaId): bool
    {
        return QuoteFormulaRange::where('id', $rangeId)
            ->where('formula_id', $formulaId)
            ->exists();
    }
}
