<?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 string $name
 * @property string|null $description
 * @property array|null $headers
 * @property array|null $path_params
 * @property array|null $query_params
 * @property array|null $body
 * @property bool $is_shared
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 */
class ApiTemplate extends Model
{
    protected $table = 'admin_api_templates';

    protected $fillable = [
        'user_id',
        'endpoint',
        'method',
        'name',
        'description',
        'headers',
        'path_params',
        'query_params',
        'body',
        'is_shared',
    ];

    protected $casts = [
        'headers' => 'array',
        'path_params' => 'array',
        'query_params' => 'array',
        'body' => 'array',
        'is_shared' => 'boolean',
    ];

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

    /**
     * 공유된 템플릿 스코프
     */
    public function scopeShared($query)
    {
        return $query->where('is_shared', true);
    }

    /**
     * 특정 엔드포인트의 템플릿 스코프
     */
    public function scopeForEndpoint($query, string $endpoint, string $method)
    {
        return $query->where('endpoint', $endpoint)->where('method', $method);
    }

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