<?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 int $user_id
 * @property string $endpoint
 * @property string $method
 * @property array|null $request_headers
 * @property array|null $request_body
 * @property int $response_status
 * @property array|null $response_headers
 * @property string|null $response_body
 * @property int $duration_ms
 * @property string $environment
 * @property \Illuminate\Support\Carbon $created_at
 */
class ApiHistory extends Model
{
    /**
     * updated_at 컬럼 없음
     */
    public const UPDATED_AT = null;

    protected $table = 'admin_api_histories';

    protected $fillable = [
        'user_id',
        'endpoint',
        'method',
        'request_headers',
        'request_body',
        'response_status',
        'response_headers',
        'response_body',
        'duration_ms',
        'environment',
    ];

    protected $casts = [
        'request_headers' => 'array',
        'request_body' => 'array',
        'response_headers' => 'array',
        'response_status' => 'integer',
        'duration_ms' => 'integer',
    ];

    /**
     * 사용자 관계
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 최근순 정렬 스코프
     */
    public function scopeLatest($query)
    {
        return $query->orderByDesc('created_at');
    }

    /**
     * HTTP 메서드 배지 색상
     */
    public function getMethodColorAttribute(): string
    {
        return match (strtoupper($this->method)) {
            'GET' => 'green',
            'POST' => 'blue',
            'PUT' => 'yellow',
            'PATCH' => 'orange',
            'DELETE' => 'red',
            default => 'gray',
        };
    }

    /**
     * 응답 상태 코드 색상
     */
    public function getStatusColorAttribute(): string
    {
        return match (true) {
            $this->response_status >= 200 && $this->response_status < 300 => 'green',
            $this->response_status >= 300 && $this->response_status < 400 => 'blue',
            $this->response_status >= 400 && $this->response_status < 500 => 'yellow',
            $this->response_status >= 500 => 'red',
            default => 'gray',
        };
    }

    /**
     * 성공 여부
     */
    public function getIsSuccessAttribute(): bool
    {
        return $this->response_status >= 200 && $this->response_status < 300;
    }
}
