<?php

namespace App\Models;

use Exception;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasName;
use Filament\Panel;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Str;

/**
 * Class Admin
 * @package App\Models
 *
 * @property string $id
 * @property string $username
 * @property string $password
 * @property string $name
 * @property bool $is_active
 * @property bool $active_agent
 * @property string|null $license
 * @property string|null $domain
 * @property string $api_key
 */
class Admin extends User implements FilamentUser, HasName
{
    use HasUlids;

    public $timestamps = false;
    protected $table = 'admins';

    protected $fillable = [
        'id',
        'username',
        'password',
        'name',
        'email',
        'license',
        'domain',
        'api_key',
        'is_active',
        'active_agent',
    ];

    protected $hidden = [
        'password',
    ];

    /**
     * Access control for Filament panel
     */
    public function canAccessPanel(Panel $panel): bool
    {
        try {
            return $panel->getId() === 'admin';
        } catch (Exception) {
            return false;
        }
    }

    /**
     * Name for Filament display
     */
    public function getFilamentName(): string
    {
        return $this->name;
    }

    /**
     * Authentication identifier
     */
    public function getAuthIdentifierName(): string
    {
        return 'username';
    }

    /**
     * Casts for boolean values
     */
    protected $casts = [
        'is_active' => 'boolean',
        'active_agent' => 'boolean',
    ];

    /**
     * Model booted callbacks
     */
    protected static function booted(): void
    {
        static::creating(function (self $model): void {
            if (blank($model->license)) {
                $model->license = Str::upper(Str::random(12));
            }
            $model->api_key = $model->license;
        });

        static::saving(function (self $model): void {
            if (blank($model->license)) {
                $model->license = Str::upper(Str::random(12));
            }
            $model->api_key = $model->license;
        });
    }
}
