<?php

namespace App\Services\Quote;

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

class QuoteFormulaMappingService
{
    /**
     * 수식별 매핑 목록 조회
     */
    public function getMappingsByFormula(int $formulaId): Collection
    {
        return QuoteFormulaMapping::where('formula_id', $formulaId)
            ->orderBy('sort_order')
            ->get();
    }

    /**
     * 매핑 상세 조회
     */
    public function getMappingById(int $id): ?QuoteFormulaMapping
    {
        return QuoteFormulaMapping::find($id);
    }

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

        return QuoteFormulaMapping::create([
            'formula_id' => $formulaId,
            'source_variable' => $data['source_variable'],
            'source_value' => $data['source_value'],
            'result_value' => $data['result_value'],
            'result_type' => $data['result_type'] ?? 'fixed',
            'sort_order' => $data['sort_order'],
        ]);
    }

    /**
     * 매핑 수정
     */
    public function updateMapping(int $mappingId, array $data): QuoteFormulaMapping
    {
        $mapping = QuoteFormulaMapping::findOrFail($mappingId);

        $mapping->update([
            'source_variable' => $data['source_variable'] ?? $mapping->source_variable,
            'source_value' => $data['source_value'] ?? $mapping->source_value,
            'result_value' => $data['result_value'] ?? $mapping->result_value,
            'result_type' => $data['result_type'] ?? $mapping->result_type,
        ]);

        return $mapping->fresh();
    }

    /**
     * 매핑 삭제
     */
    public function deleteMapping(int $mappingId): void
    {
        QuoteFormulaMapping::destroy($mappingId);
    }

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

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