<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes;

    public const ROLE_SUPER_ADMIN = 'super_admin';
    public const ROLE_ADMIN = 'admin';
    public const ROLE_SERVER_ADMIN = 'server_admin';
    public const ROLE_SUPPORT = 'support';
    public const ROLE_VIEWER = 'viewer';
    // AI Portal calls the bottom rung "observer" — alias kept for code paths
    // copied verbatim from the portal. Functionally identical to viewer.
    public const ROLE_OBSERVER = 'observer';

    public const ROLES = [
        self::ROLE_SUPER_ADMIN,
        self::ROLE_ADMIN,
        self::ROLE_SERVER_ADMIN,
        self::ROLE_SUPPORT,
        self::ROLE_VIEWER,
        self::ROLE_OBSERVER,
    ];

    protected $fillable = [
        'name', 'email', 'password', 'avatar', 'role', 'status',
        'phone', 'timezone', 'slack_user_id', 'telegram_user_id', 'snoozed_until',
        'two_fa_enabled', 'two_fa_secret', 'preferences',
        // AI Portal additions
        'totp_secret', 'totp_confirmed', 'webauthn_credentials',
        'failed_login_attempts', 'locked_until', 'last_login_at', 'reply_tone',
    ];

    protected $hidden = [
        'password', 'remember_token', 'two_fa_secret',
        'totp_secret', 'webauthn_credentials',
    ];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'last_seen_at' => 'datetime',
            'password' => 'hashed',
            'two_fa_enabled' => 'boolean',
            'two_fa_secret' => 'encrypted',
            'preferences' => 'array',
            // AI Portal additions
            'totp_secret'           => 'encrypted',
            'webauthn_credentials'  => 'encrypted:json',
            'totp_confirmed'        => 'boolean',
            'failed_login_attempts' => 'integer',
            'locked_until'          => 'datetime',
            'last_login_at'         => 'datetime',
        ];
    }

    /* ---------------- Permission helpers ---------------- */

    public function hasRole(string ...$roles): bool
    {
        return in_array($this->role, $roles, true);
    }

    public function isSuperAdmin(): bool
    {
        return $this->role === self::ROLE_SUPER_ADMIN;
    }

    public function isAdminOrAbove(): bool
    {
        return in_array($this->role, [self::ROLE_SUPER_ADMIN, self::ROLE_ADMIN], true);
    }

    public function canManageServers(): bool
    {
        return in_array($this->role, [
            self::ROLE_SUPER_ADMIN,
            self::ROLE_ADMIN,
            self::ROLE_SERVER_ADMIN,
        ], true);
    }

    public function canAcknowledgeIncidents(): bool
    {
        return ! in_array($this->role, [self::ROLE_VIEWER, self::ROLE_OBSERVER], true);
    }

    // AI Portal helpers — kept here so controllers ported verbatim continue
    // to compile against this model.
    public function canApproveActions(): bool { return $this->canManageServers(); }
    public function canHandleTickets(): bool
    {
        return in_array($this->role, [
            self::ROLE_SUPER_ADMIN, self::ROLE_ADMIN, self::ROLE_SUPPORT,
        ], true);
    }
    public function isLocked(): bool
    {
        return $this->locked_until && $this->locked_until->isFuture();
    }

    public function canManageUsers(): bool
    {
        return $this->isAdminOrAbove();
    }

    public function canModifySettings(): bool
    {
        return $this->isSuperAdmin();
    }

    /* ---------------- Relationships ---------------- */

    public function notifications()
    {
        return $this->hasMany(Notification::class);
    }

    public function assignedIncidents()
    {
        return $this->hasMany(Incident::class, 'assigned_to');
    }

    public function activityLogs()
    {
        return $this->hasMany(ActivityLog::class);
    }

    public function notificationPreference()
    {
        return $this->hasOne(NotificationPreference::class);
    }

    public function fcmTokens()
    {
        return $this->hasMany(FcmToken::class);
    }

    public function onCallShifts()
    {
        return $this->hasMany(\App\Models\OnCallShift::class);
    }

    public function approvedActions()
    {
        return $this->hasMany(AiAction::class, 'approved_by');
    }
}
