<?php

namespace App\Models;

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

class UserSession extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'session_id',
        'ip_address',
        'user_agent',
        'device_type',
        'browser',
        'platform',
        'location',
        'is_current',
        'last_activity',
        'created_at',
    ];

    /**
     * Disable updated_at since the table only tracks created_at and last_activity.
     */
    const UPDATED_AT = null;

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'last_activity' => 'datetime',
        'created_at' => 'datetime',
        'is_current' => 'boolean',
    ];

    /**
     * Device types.
     */
    const DEVICE_DESKTOP = 'desktop';
    const DEVICE_MOBILE = 'mobile';
    const DEVICE_TABLET = 'tablet';
    const DEVICE_UNKNOWN = 'unknown';

    /**
     * Get the user that owns the session.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Scope a query to filter by user.
     */
    public function scopeForUser($query, int $userId)
    {
        return $query->where('user_id', $userId);
    }

    /**
     * Scope a query to only include current session.
     */
    public function scopeCurrent($query)
    {
        return $query->where('is_current', true);
    }

    /**
     * Scope a query to order by last activity.
     */
    public function scopeOrderByActivity($query, string $direction = 'desc')
    {
        return $query->orderBy('last_activity', $direction);
    }

    /**
     * Parse user agent to detect device type.
     *
     * @param string $userAgent
     * @return string
     */
    public static function detectDeviceType(string $userAgent): string
    {
        $userAgent = strtolower($userAgent);

        if (preg_match('/tablet|ipad|playbook|silk/', $userAgent)) {
            return self::DEVICE_TABLET;
        }

        if (preg_match('/mobile|android|iphone|ipod|blackberry|opera mini|iemobile/', $userAgent)) {
            return self::DEVICE_MOBILE;
        }

        if (preg_match('/windows|macintosh|linux|ubuntu/', $userAgent)) {
            return self::DEVICE_DESKTOP;
        }

        return self::DEVICE_UNKNOWN;
    }

    /**
     * Parse user agent to detect browser.
     *
     * @param string $userAgent
     * @return string
     */
    public static function detectBrowser(string $userAgent): string
    {
        $browsers = [
            'Chrome' => '/chrome/i',
            'Firefox' => '/firefox/i',
            'Safari' => '/safari/i',
            'Edge' => '/edge/i',
            'Opera' => '/opera|opr/i',
            'IE' => '/msie|trident/i',
        ];

        foreach ($browsers as $browser => $pattern) {
            if (preg_match($pattern, $userAgent)) {
                return $browser;
            }
        }

        return 'Unknown';
    }

    /**
     * Parse user agent to detect platform.
     *
     * @param string $userAgent
     * @return string
     */
    public static function detectPlatform(string $userAgent): string
    {
        $platforms = [
            'Windows' => '/windows|win32|win64/i',
            'macOS' => '/macintosh|mac os x/i',
            'Linux' => '/linux|ubuntu|fedora/i',
            'iOS' => '/iphone|ipad|ipod/i',
            'Android' => '/android/i',
        ];

        foreach ($platforms as $platform => $pattern) {
            if (preg_match($pattern, $userAgent)) {
                return $platform;
            }
        }

        return 'Unknown';
    }

    /**
     * Check if session is expired.
     *
     * @param int $lifetime Session lifetime in minutes
     * @return bool
     */
    public function isExpired(int $lifetime = 120): bool
    {
        return $this->last_activity->addMinutes($lifetime)->isPast();
    }

    /**
     * Mark session as current.
     */
    public function markAsCurrent(): void
    {
        $this->update(['is_current' => true]);
    }
}
