<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class AdminSession extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'ip_address',
        'user_agent',
        'session_token',
        'login_at',
        'last_activity_at',
        'logout_at',
        'is_active',
        'login_method',
        'metadata',
    ];

    protected $casts = [
        'login_at' => 'datetime',
        'last_activity_at' => 'datetime',
        'logout_at' => 'datetime',
        'is_active' => 'boolean',
        'metadata' => 'array',
    ];

    /**
     * Admin user who owns this session
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Check if session is still active
     */
    public function isActive(): bool
    {
        return $this->is_active && $this->logout_at === null;
    }

    /**
     * Get session duration in seconds
     */
    public function getDuration(): int
    {
        $endTime = $this->logout_at ?? now();
        return (int) $endTime->diffInSeconds($this->login_at);
    }

    /**
     * Get time since last activity
     */
    public function getIdleSeconds(): int
    {
        return (int) now()->diffInSeconds($this->last_activity_at);
    }

    /**
     * Update last activity timestamp
     */
    public function touchActivity(): void
    {
        $this->update(['last_activity_at' => now()]);
    }

    /**
     * Logout this session
     */
    public function logout(): void
    {
        $this->update([
            'is_active' => false,
            'logout_at' => now(),
        ]);
    }

    /**
     * Scope to active sessions
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->whereNull('logout_at');
    }

    /**
     * Scope to sessions for a specific user
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope to sessions older than X hours
     */
    public function scopeOlderThan($query, int $hours)
    {
        return $query->where('created_at', '<', now()->subHours($hours));
    }
}

