<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

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

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

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

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password'          => 'hashed',
    ];

    // ── Relations ──────────────────────────────────────────────────────────

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function deviceSessions()
    {
        return $this->hasMany(DeviceSession::class);
    }

    // ── Helpers ────────────────────────────────────────────────────────────

    public function isSuperAdmin(): bool
    {
        return $this->hasRole('super_admin');
    }

    public function isAdmin(): bool
    {
        return $this->hasRole('admin');
    }

    public function getActiveSessionCount(): int
    {
        return $this->deviceSessions()->where('is_active', true)->count();
    }

    public function revokeAllOtherSessions(string $currentDeviceId): void
    {
        $this->deviceSessions()
            ->where('device_id', '!=', $currentDeviceId)
            ->update(['is_active' => false]);

        // Revoke all tokens except current
        $this->tokens()
            ->where('name', '!=', $currentDeviceId)
            ->delete();
    }
}
