<?php

namespace App\Models\Coocon;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * 쿠콘 API 설정 모델
 *
 * @property int $id
 * @property string $name
 * @property string $environment
 * @property string $api_key
 * @property string $base_url
 * @property string|null $description
 * @property bool $is_active
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property \Carbon\Carbon|null $deleted_at
 */
class CooconConfig extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'environment',
        'api_key',
        'base_url',
        'description',
        'is_active',
    ];

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

    /**
     * 활성화된 테스트 서버 설정 조회
     */
    public static function getActiveTest(): ?self
    {
        return self::where('environment', 'test')
            ->where('is_active', true)
            ->first();
    }

    /**
     * 활성화된 운영 서버 설정 조회
     */
    public static function getActiveProduction(): ?self
    {
        return self::where('environment', 'production')
            ->where('is_active', true)
            ->first();
    }

    /**
     * 현재 환경에 맞는 활성 설정 조회
     */
    public static function getActive(bool $isTestMode = false): ?self
    {
        return $isTestMode ? self::getActiveTest() : self::getActiveProduction();
    }

    /**
     * 환경 라벨
     */
    public function getEnvironmentLabelAttribute(): string
    {
        return match ($this->environment) {
            'test' => '테스트서버',
            'production' => '운영서버',
            default => $this->environment,
        };
    }

    /**
     * 상태 라벨
     */
    public function getStatusLabelAttribute(): string
    {
        return $this->is_active ? '활성' : '비활성';
    }

    /**
     * 상태 색상 (Tailwind)
     */
    public function getStatusColorAttribute(): string
    {
        return $this->is_active ? 'green' : 'gray';
    }

    /**
     * 마스킹된 API 키 (앞 8자리만 표시)
     */
    public function getMaskedApiKeyAttribute(): string
    {
        if (strlen($this->api_key) <= 8) {
            return $this->api_key;
        }

        return substr($this->api_key, 0, 8).str_repeat('*', 8).'...';
    }
}
