<?php

namespace App\Domain\Shared\Models;

use App\Infrastructure\Encryption\Casts\TeamEncryptedArray;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;

/**
 * @property string $id
 * @property string $team_id
 * @property string $provider
 * @property string|null $name
 * @property array<string, mixed>|null $credentials
 * @property bool $is_active
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @property-read Team $team
 */
class TeamProviderCredential extends Model
{
    use HasUuids;

    protected $fillable = [
        'team_id',
        'provider',
        'name',
        'credentials',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'credentials' => TeamEncryptedArray::class,
            'is_active' => 'boolean',
        ];
    }

    protected $hidden = [
        'credentials',
    ];

    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }

    /**
     * Scope to only custom AI endpoints (provider='custom_endpoint').
     */
    public function scopeCustomEndpoints($query)
    {
        return $query->where('provider', 'custom_endpoint');
    }

    /**
     * Get masked API key for display (last 4 characters).
     */
    public function getMaskedApiKeyAttribute(): ?string
    {
        $key = $this->credentials['api_key'] ?? null;

        if (! $key || strlen($key) < 5) {
            return $key ? '****' : null;
        }

        return str_repeat('*', strlen($key) - 4).substr($key, -4);
    }
}
