<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AiProvider extends Model
{
    public const PURPOSES = [
        'ticket_draft'   => 'Ticket reply drafts (customer-facing)',
        'ticket_invest'  => 'Ticket investigation (admin notes)',
        'server_audit'   => 'Server health audit findings',
        'server_chat'    => 'Per-server AI chat (interactive)',
        'anomaly_detect' => 'Anomaly detection in audit logs',
        'default'        => 'Fallback for any unspecified purpose',
    ];

    public const AUTH_API_KEY = 'api_key';
    public const AUTH_OAUTH   = 'oauth';

    protected $fillable = [
        'label', 'provider', 'auth_type', 'model', 'api_key', 'base_url',
        'refresh_token', 'token_expires_at', 'oauth_account',
        'purposes', 'enabled', 'created_by',
        'last_tested_at', 'last_test_result', 'last_test_ok',
    ];

    protected $casts = [
        'api_key'           => 'encrypted',
        'refresh_token'     => 'encrypted',
        'purposes'          => 'array',
        'enabled'           => 'boolean',
        'last_test_ok'      => 'boolean',
        'last_tested_at'    => 'datetime',
        'token_expires_at'  => 'datetime',
    ];

    protected $hidden = ['api_key'];

    /** Mask the key for API responses — only last 4 chars visible. */
    public function maskedKey(): string
    {
        $k = (string) $this->api_key;
        if (! $k) return '';
        return strlen($k) > 8
            ? str_repeat('•', 8) . substr($k, -4)
            : str_repeat('•', strlen($k));
    }
}
