<?php

namespace App\Providers;

use App\Domains\Notification\Events\TicketsAvailable;
use App\Domains\Notification\Events\UserRegistered;
use App\Domains\Notification\Listeners\SendPurchasePaidEmail;
use App\Domains\Notification\Listeners\SendTicketsAvailableEmail;
use App\Domains\Notification\Listeners\SendWelcomeEmail;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Ticket\Listeners\GenerateTicketsForPaidPurchase;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Event::listen(PurchasePaid::class, SendPurchasePaidEmail::class);
        Event::listen(PurchasePaid::class, GenerateTicketsForPaidPurchase::class);
        Event::listen(TicketsAvailable::class, SendTicketsAvailableEmail::class);
        Event::listen(UserRegistered::class, SendWelcomeEmail::class);

        Builder::macro('paginateFromRequest', function (int $defaultPerPage = 15, int $maxPerPage = 100, ?int $page = null) {
            /** @var Builder $this */
            $perPage = (int) request()->query('per_page', $defaultPerPage);
            $page = $page ?? (int) request()->query('page', 1);

            if ($perPage <= 0) {
                $perPage = $defaultPerPage;
            }
            if ($perPage > $maxPerPage) {
                $perPage = $maxPerPage;
            }
            if ($page <= 0) {
                $page = 1;
            }

            return $this->paginate(perPage: $perPage, page: $page);
        });
    }
}
