<?php

namespace App\Master\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Mtc\MercuryDataModels\User;
use Stancl\Tenancy\Database\Concerns\CentralConnection;

class ImpersonationRequest extends Model
{
    use CentralConnection;

    protected $table = 'impersonation_requests';

    protected $fillable = [
        'requester_id',
        'target_user_id',
        'reason',
        'status',
        'actioned_by',
        'actioned_at',
        'admin_notes',
        'session_id',
        'expires_at',
        'used_at',
    ];

    protected $casts = [
        'actioned_at' => 'datetime',
        'expires_at' => 'datetime',
        'used_at' => 'datetime',
    ];

    public function requester(): BelongsTo
    {
        return $this->belongsTo(User::class, 'requester_id');
    }

    public function targetUser(): BelongsTo
    {
        return $this->belongsTo(User::class, 'target_user_id');
    }

    public function actionedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'actioned_by');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }

    public function scopeRejected($query)
    {
        return $query->where('status', 'rejected');
    }

    public function scopeUsable($query, ?string $sessionId = null)
    {
        return $query->where('status', 'approved')
            ->where(function ($q) {
                $q->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->whereNull('used_at')
            ->when($sessionId, fn ($q) => $q->where('session_id', $sessionId));
    }

    public function isPending(): bool
    {
        return $this->status === 'pending';
    }

    public function isApproved(): bool
    {
        return $this->status === 'approved';
    }

    public function isRejected(): bool
    {
        return $this->status === 'rejected';
    }

    public function isUsed(): bool
    {
        return $this->used_at !== null;
    }

    public function isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }
}
