<?php

namespace App\Models\Approvals;

use App\Models\User;
use App\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class ApprovalForm extends Model
{
    use BelongsToTenant, SoftDeletes;

    protected $table = 'approval_forms';

    protected $casts = [
        'template' => 'array',
        'is_active' => 'boolean',
    ];

    protected $fillable = [
        'tenant_id',
        'name',
        'code',
        'category',
        'template',
        'is_active',
        'created_by',
        'updated_by',
        'deleted_by',
    ];

    // =========================================================================
    // 카테고리 상수
    // =========================================================================

    public const CATEGORY_REQUEST = 'request';

    public const CATEGORY_EXPENSE = 'expense';

    public const CATEGORY_EXPENSE_ESTIMATE = 'expense_estimate';

    public const CATEGORIES = [
        self::CATEGORY_REQUEST,
        self::CATEGORY_EXPENSE,
        self::CATEGORY_EXPENSE_ESTIMATE,
    ];

    // =========================================================================
    // 관계 정의
    // =========================================================================

    public function approvals(): HasMany
    {
        return $this->hasMany(Approval::class, 'form_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    // =========================================================================
    // 스코프
    // =========================================================================

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeCategory($query, string $category)
    {
        return $query->where('category', $category);
    }

    // =========================================================================
    // 헬퍼 메서드
    // =========================================================================

    public function getCategoryLabelAttribute(): string
    {
        return match ($this->category) {
            self::CATEGORY_REQUEST => '품의서',
            self::CATEGORY_EXPENSE => '지출결의서',
            self::CATEGORY_EXPENSE_ESTIMATE => '지출 예상 내역서',
            default => $this->category ?? '',
        };
    }
}
