<?php

namespace App\Queries;

use App\Enums\PaymentStatus;
use App\Enums\RegistrationStatus;
use App\Models\EventRegistration;
use App\Models\User;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;

class EventRegistrationQuery
{
    public function forUser(User $user, array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = EventRegistration::query()
            ->with(['event.game', 'paymentProofs'])
            ->where('user_id', $user->id)
            ->orderByDesc('registered_at');

        $this->applyFilters($query, $filters);

        return $query->paginate($perPage)->withQueryString();
    }

    public function pendingReview(int $perPage = 20): LengthAwarePaginator
    {
        return EventRegistration::query()
            ->with(['event.game', 'user', 'playerGameProfile'])
            ->where('status', RegistrationStatus::Pending)
            ->orderBy('registered_at')
            ->paginate($perPage);
    }

    public function pendingPaymentProofs(int $perPage = 20): LengthAwarePaginator
    {
        return EventRegistration::query()
            ->with(['event.game', 'user', 'paymentProofs'])
            ->where('status', RegistrationStatus::PaymentReview)
            ->where('payment_status', PaymentStatus::ProofSubmitted)
            ->orderBy('registered_at')
            ->paginate($perPage);
    }

    public function waitlistedForEvent(int $eventId): Collection
    {
        return EventRegistration::query()
            ->with(['user', 'playerGameProfile'])
            ->where('event_id', $eventId)
            ->where('status', RegistrationStatus::Waitlisted)
            ->orderBy('waitlist_position')
            ->get();
    }

    private function applyFilters(Builder $query, array $filters): void
    {
        if (filled($filters['status'] ?? null)) {
            $query->where('status', $filters['status']);
        }

        if (filled($filters['payment_status'] ?? null)) {
            $query->where('payment_status', $filters['payment_status']);
        }

        if (($filters['upcoming'] ?? false) === true) {
            $query->whereHas('event', fn (Builder $q) => $q->where('starts_at', '>=', now()));
        }

        if (($filters['past'] ?? false) === true) {
            $query->whereHas('event', fn (Builder $q) => $q->where('ends_at', '<', now()));
        }
    }
}
