<?php

namespace App\Domains\Ticket\Listeners;

use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Services\TicketGeneratorService;

class GenerateTicketsForPaidPurchase
{
    public function __construct(
        private readonly TicketGeneratorService $ticketGenerator,
    ) {}

    public function handle(PurchasePaid $event): void
    {
        $purchase = Purchase::query()
            ->with(['user', 'items'])
            ->findOrFail($event->purchaseId);
        $user = $purchase->user;
        foreach ($purchase->items as $purchaseItem) {
            $catalogItem = CatalogItem::query()
                ->where('tenant_code', $purchase->tenant_codigo)
                ->find($purchaseItem->source_catalog_item_id);

            if ($catalogItem === null) {
                throw TicketGenerationException::catalogItemNotFound($purchaseItem);
            }

            if (! $this->requiresTickets($catalogItem)) {
                continue;
            }

            if ($user === null) {
                throw TicketGenerationException::purchaseWithoutUser($purchase);
            }

            $this->ticketGenerator->generate(
                $catalogItem,
                $user,
                $purchaseItem->cantidad,
                $purchaseItem->source_variant_id,
                $purchase->getKey(),
            );
        }
    }

    private function requiresTickets(CatalogItem $catalogItem): bool
    {
        if (! $catalogItem->isBundle()) {
            return $catalogItem->has_tickets;
        }

        return $catalogItem->bundleComponents()
            ->whereHas(
                'catalogItem',
                fn ($query) => $query->where('has_tickets', true),
            )
            ->exists();
    }
}
