<?php

namespace App\Models\Calculation;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class CalculationConfig extends Model
{
    protected $table = 'calculation_configs';

    protected $fillable = [
        'tenant_id',
        'company_name',
        'formula_type',
        'version',
        'formula_expression',
        'parameters',
        'conditions',
        'validation_rules',
        'description',
        'is_active',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'parameters' => 'array',
        'conditions' => 'array',
        'validation_rules' => 'array',
        'is_active' => 'boolean',
    ];

    /**
     * 테넌트별 스코프
     */
    public function scopeForTenant(Builder $query, int $tenantId): Builder
    {
        return $query->where('tenant_id', $tenantId);
    }

    /**
     * 활성화된 설정만 조회
     */
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    /**
     * 업체별 산출식 조회
     */
    public function scopeForCompany(Builder $query, string $companyName): Builder
    {
        return $query->where('company_name', $companyName);
    }

    /**
     * 산출식 타입별 조회
     */
    public function scopeForType(Builder $query, string $formulaType): Builder
    {
        return $query->where('formula_type', $formulaType);
    }

    /**
     * 최신 버전 조회
     */
    public function scopeLatestVersion(Builder $query): Builder
    {
        return $query->orderByDesc('version');
    }

    /**
     * 업체별 활성 산출식 목록 조회
     */
    public static function getActiveFormulasForCompany(int $tenantId, string $companyName): array
    {
        return static::forTenant($tenantId)
            ->forCompany($companyName)
            ->active()
            ->get()
            ->groupBy('formula_type')
            ->map(function ($formulas) {
                return $formulas->sortByDesc('version')->first();
            })
            ->toArray();
    }

    /**
     * 특정 산출식 조회 (최신 버전)
     */
    public static function getLatestFormula(int $tenantId, string $companyName, string $formulaType): ?static
    {
        return static::forTenant($tenantId)
            ->forCompany($companyName)
            ->forType($formulaType)
            ->active()
            ->latestVersion()
            ->first();
    }
}
