<?php

namespace App\Models;

use App\Models\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Spatie\Permission\Traits\HasRoles;

/**
 * An operator: the owner of CluPilot, or a member of staff.
 *
 * Extends Authenticatable rather than App\Models\User — sharing the class would
 * put both groups back in one table, which is the thing this exists to end.
 *
 * `$guard_name` is what makes Spatie resolve roles against the `operator` guard.
 * Without it every role assignment would be checked against `web` and fail,
 * which is the failure mode to expect if roles suddenly stop matching.
 */
class Operator extends Authenticatable
{
    use HasFactory, HasRoles, HasUuid, Notifiable, TwoFactorAuthenticatable;

    /** Tells spatie/laravel-permission which guard this model's roles live under. */
    protected string $guard_name = 'operator';

    /** The six roles that grant access to the console. */
    public const OPERATOR_ROLES = ['Owner', 'Admin', 'Support', 'Billing', 'Read-only', 'Developer'];

    protected $fillable = ['name', 'email', 'password', 'last_login_at', 'disabled_at'];

    protected $hidden = ['password', 'remember_token', 'two_factor_secret', 'two_factor_recovery_codes'];

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
            'last_login_at' => 'datetime',
            'disabled_at' => 'datetime',
            'two_factor_confirmed_at' => 'datetime',
        ];
    }

    /** True when this operator holds a role that reaches the console. */
    public function isOperator(): bool
    {
        return $this->hasAnyRole(self::OPERATOR_ROLES);
    }

    /** A disabled operator keeps their record and loses their access. */
    public function isActive(): bool
    {
        return $this->disabled_at === null;
    }
}
