<?php

namespace App\Master\Models;

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

class LiveSiteAccessRequest extends Model
{
    use CentralConnection;

    protected $table = 'live_site_access_requests';

    protected $fillable = [
        'requester_id',
        'tenant_id',
        'reason',
        'status',
        'actioned_by',
        'actioned_at',
        'admin_notes',
        'session_id',
        'expires_at',
        'first_used_at',
        'last_used_at',
    ];

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

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

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

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

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

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

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

    public function scopeUsable(
        Builder $query,
        string $tenantId,
        int $requesterId,
        ?string $sessionId = null
    ): Builder {
        return $query->where('status', 'approved')
            ->where('tenant_id', $tenantId)
            ->where('requester_id', $requesterId)
            ->where(function ($q) {
                $q->whereNull('expires_at')
                    ->orWhere('expires_at', '>', now());
            })
            ->when(
                $sessionId !== null,
                fn ($q) => $q->where(function ($q) use ($sessionId) {
                    $q->whereNull('session_id')->orWhere('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 isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }

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

    public function consume(string $sessionId): void
    {
        $this->update([
            'session_id' => $this->session_id ?? $sessionId,
            'first_used_at' => $this->first_used_at ?? now(),
            'last_used_at' => now(),
        ]);
    }
}
