<?php

namespace App\Models;

use Exception;
use Filament\Models\Contracts\FilamentUser;
use Filament\Models\Contracts\HasName;
use Filament\Panel;
use Filament\Facades\Filament;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Auth;

/**
 * Class Agent
 * @package App\Models
 *
 * @property string $id
 * @property string|null $admin_id
 * @property string $username
 * @property string $password
 * @property string $name
 * @property bool $is_active
 *
 * @property Collection<Inquiry> $inquiries
 * @property Collection<Session> $sessions
 */
class Agent extends User implements FilamentUser, HasName
{
    use HasUlids;

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

    protected $fillable = [
        'id',
        'admin_id',
        'username',
        'password',
        'name',
        'email',
        'is_active',
    ];

    protected $hidden = [
        'password',
    ];

    /**
     * Relations
     */
    public function inquiries(): HasMany
    {
        return $this->hasMany(Inquiry::class, 'agent_id');
    }

    public function sessions(): HasMany
    {
        return $this->hasMany(Session::class, 'agent_id');
    }

    public function admin()
    {
        return $this->belongsTo(Admin::class, 'admin_id');
    }

    /**
     * Access control for Filament panel
     */
    public function canAccessPanel(Panel $panel): bool
    {
        try {
            return $panel->getId() === 'agent';
        } 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',
    ];

    /**
     * Model booted callbacks
     */
    protected static function booted(): void
    {
        static::saving(function (Agent $agent): void {
            // Attach agent to currently logged-in admin
            $adminId = null;

            // Prefer Filament admin panel
            if (Filament::getCurrentPanel()?->getId() === 'admin') {
                $adminId = Filament::auth()?->id();
            }

            // Fallbacks
            $adminId ??= Auth::guard('admin')->id();
            $adminId ??= Auth::id();

            if ($adminId) {
                $agent->admin_id = $adminId;
            }
        });
    }
}
