<?php

namespace App\Models\DevTools;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * API 폐기 후보 모델
 *
 * @property int $id
 * @property string $endpoint
 * @property string $method
 * @property string $status
 * @property string|null $reason
 * @property \Illuminate\Support\Carbon|null $scheduled_date
 * @property \Illuminate\Support\Carbon|null $deprecated_date
 * @property int|null $created_by
 * @property \Illuminate\Support\Carbon $created_at
 * @property \Illuminate\Support\Carbon $updated_at
 */
class ApiDeprecation extends Model
{
    protected $table = 'admin_api_deprecations';

    protected $fillable = [
        'endpoint',
        'method',
        'status',
        'reason',
        'scheduled_date',
        'deprecated_date',
        'created_by',
    ];

    protected $casts = [
        'scheduled_date' => 'date',
        'deprecated_date' => 'date',
    ];

    /**
     * 상태 상수
     */
    public const STATUS_CANDIDATE = 'candidate';     // 삭제 후보

    public const STATUS_SCHEDULED = 'scheduled';     // 삭제 예정

    public const STATUS_DEPRECATED = 'deprecated';   // 폐기됨 (사용 중단)

    public const STATUS_REMOVED = 'removed';         // 완전 삭제

    /**
     * 상태 라벨
     */
    public static function statusLabels(): array
    {
        return [
            self::STATUS_CANDIDATE => '삭제 후보',
            self::STATUS_SCHEDULED => '삭제 예정',
            self::STATUS_DEPRECATED => '폐기됨',
            self::STATUS_REMOVED => '삭제됨',
        ];
    }

    /**
     * 상태 라벨 접근자
     */
    public function getStatusLabelAttribute(): string
    {
        return self::statusLabels()[$this->status] ?? $this->status;
    }

    /**
     * 상태 색상 접근자
     */
    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            self::STATUS_CANDIDATE => 'yellow',
            self::STATUS_SCHEDULED => 'orange',
            self::STATUS_DEPRECATED => 'red',
            self::STATUS_REMOVED => 'gray',
            default => 'gray',
        };
    }

    /**
     * 생성자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * 후보 상태 스코프
     */
    public function scopeCandidates($query)
    {
        return $query->where('status', self::STATUS_CANDIDATE);
    }

    /**
     * 활성 상태 스코프 (삭제되지 않은 것들)
     */
    public function scopeActive($query)
    {
        return $query->whereIn('status', [
            self::STATUS_CANDIDATE,
            self::STATUS_SCHEDULED,
            self::STATUS_DEPRECATED,
        ]);
    }
}
