<?php

namespace Tests\Feature\Ticket;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Catalog\Enums\CatalogItemType;
use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Services\CatalogService;
use App\Domains\Event\Models\EventDate;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Shared\Enums\FieldType;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Ticket\Enums\ValidityTimeType;
use App\Domains\Ticket\Exceptions\TicketGenerationException;
use App\Domains\Ticket\Models\ValidityTime;
use App\Domains\Ticket\Services\TicketGeneratorService;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;

class TicketGeneratorServiceTest extends TestCase
{
    use RefreshDatabase;

    private TicketGeneratorService $service;

    private Tenant $tenant;

    private User $user;

    protected function setUp(): void
    {
        parent::setUp();

        Carbon::setTestNow('2026-07-21 10:00:00');
        Queue::fake();
        $this->service = app(TicketGeneratorService::class);
        $this->tenant = $this->createTenant();
        $this->user = User::factory()->create();
    }

    protected function tearDown(): void
    {
        Carbon::setTestNow();

        parent::tearDown();
    }

    public function test_it_generates_tickets_from_a_standard_catalog_item(): void
    {
        $item = $this->createTicketableItem('single-day');

        $tickets = $this->service->generate($item, $this->user, 2);

        $this->assertCount(2, $tickets);
        foreach ($tickets as $ticket) {
            $this->assertTrue(Str::isUuid($ticket->ticket));
            $this->assertSame($this->tenant->codigo, $ticket->tenant_code);
            $this->assertSame($this->user->id, $ticket->user_id);
            $this->assertSame($item->nombre, $ticket->name);
            $this->assertSame($item->descripcion, $ticket->description);
            $this->assertSame($item->id, $ticket->source_catalog_item_id);
            $this->assertNull($ticket->source_variant_id);
            $this->assertTrue($ticket->resolvedValidityGroups()->isEmpty());
        }

        $this->assertDatabaseHas('tickets', [
            'id' => $tickets->first()->id,
            'name' => null,
            'description' => null,
        ]);
    }

    public function test_it_rejects_an_item_without_tickets_enabled(): void
    {
        $item = $this->createTicketableItem('disabled');
        $item->update(['has_tickets' => false]);

        $this->expectException(TicketGenerationException::class);
        $this->expectExceptionMessage('no tiene tickets habilitados');

        $this->service->generate($item->fresh(), $this->user);
    }

    public function test_variant_properties_are_appended_to_the_ticket_name(): void
    {
        $item = $this->createTicketableItem('shirt');
        $color = Attribute::query()->create([
            'tenant_codigo' => $this->tenant->codigo,
            'codigo' => 'color',
            'nombre' => 'Color',
            'type' => FieldType::Select,
        ]);
        $color->options()->create([
            'value' => 'black',
            'label' => 'Negro',
        ]);
        $color->options()->create([
            'value' => 'blue',
            'label' => 'Azul',
        ]);
        $size = Attribute::query()->create([
            'tenant_codigo' => $this->tenant->codigo,
            'codigo' => 'size',
            'nombre' => 'Talle',
            'type' => FieldType::Select,
        ]);
        $size->options()->create([
            'value' => 'xl',
            'label' => 'XL',
        ]);
        $itemColor = $item->itemAttributes()->create([
            'attribute_id' => $color->id,
            'sort_order' => 1,
        ]);
        $itemSize = $item->itemAttributes()->create([
            'attribute_id' => $size->id,
            'sort_order' => 2,
            'ticket_label' => 'Talle',
        ]);
        $variant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create()->id,
            'descripcion' => 'Descripción de la variante',
        ]);
        $variant->definitions()->createMany([
            ['item_attribute_id' => $itemColor->id, 'value' => 'black'],
            ['item_attribute_id' => $itemSize->id, 'value' => 'xl'],
        ]);
        $colorDefinition = $variant->definitions()
            ->where('item_attribute_id', $itemColor->id)
            ->sole();

        $ticket = $this->service
            ->generate($item, $this->user, 1, $variant->id)
            ->sole();

        $this->assertSame('Shirt (Negro, Talle XL)', $ticket->name);
        $this->assertSame('Descripción de la variante', $ticket->description);

        $item->update([
            'nombre' => 'Remera',
            'descripcion' => 'Descripción actualizada del producto',
        ]);
        $colorDefinition->update(['value' => 'blue']);
        $variant->update(['descripcion' => 'Descripción actualizada de la variante']);
        $ticket = $ticket->fresh();

        $this->assertSame('Remera (Azul, Talle XL)', $ticket->name);
        $this->assertSame('Descripción actualizada de la variante', $ticket->description);
    }

    public function test_it_generates_tickets_for_every_bundle_component_and_quantity(): void
    {
        $first = $this->createTicketableItem('first');
        $second = $this->createTicketableItem('second');
        $bundle = $this->createBundle('bundle');
        $bundle->bundleComponents()->createMany([
            ['component_catalog_item_id' => $first->id, 'quantity' => 2],
            ['component_catalog_item_id' => $second->id, 'quantity' => 1],
        ]);

        $tickets = $this->service->generate($bundle, $this->user, 2);

        $this->assertCount(6, $tickets);
        $this->assertCount(4, $tickets->where('source_catalog_item_id', $first->id));
        $this->assertCount(2, $tickets->where('source_catalog_item_id', $second->id));
        $this->assertCount(4, $tickets->where('name', $first->nombre));
        $this->assertCount(2, $tickets->where('name', $second->nombre));
    }

    public function test_bundle_component_preserves_its_source_variant(): void
    {
        $component = $this->createTicketableItem('variant-component');
        $inventory = Inventory::query()->create();
        $variant = $component->variants()->create([
            'inventory_id' => $inventory->id,
        ]);
        $bundle = $this->createBundle('variant-bundle');
        $bundle->bundleComponents()->create([
            'component_catalog_item_id' => $component->id,
            'component_variant_id' => $variant->id,
            'quantity' => 1,
        ]);

        $ticket = $this->service
            ->generate($bundle, $this->user)
            ->firstOrFail();

        $this->assertSame($component->id, $ticket->source_catalog_item_id);
        $this->assertSame($variant->id, $ticket->source_variant_id);
    }

    public function test_bundle_generation_is_rolled_back_when_a_component_is_invalid(): void
    {
        $valid = $this->createTicketableItem('valid');
        $invalid = $this->createTicketableItem('invalid');
        $invalid->update(['has_tickets' => false]);
        $bundle = $this->createBundle('invalid-bundle');
        $bundle->bundleComponents()->createMany([
            ['component_catalog_item_id' => $valid->id, 'quantity' => 1],
            ['component_catalog_item_id' => $invalid->id, 'quantity' => 1],
        ]);

        try {
            $this->service->generate($bundle, $this->user);
            $this->fail('La generación debería haber fallado.');
        } catch (TicketGenerationException) {
            $this->assertDatabaseCount('tickets', 0);
        }
    }

    public function test_marking_a_purchase_as_paid_generates_its_tickets_once(): void
    {
        $item = $this->createTicketableItem('paid-ticket');
        $purchase = $this->createPurchase($item, 2);
        $purchase->setRelation('items', new EloquentCollection);

        $purchase->markAsPaid();

        $this->assertSame(Purchase::STATUS_PAID, $purchase->status);
        $this->assertDatabaseCount('tickets', 2);

        $this->actingAs($this->user, 'sanctum')
            ->getJson("/api/tenants/{$this->tenant->codigo}/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.tickets_count', 2)
            ->assertJsonPath('data.has_generated_tickets', true);

        $purchase->markAsPaid();

        $this->assertDatabaseCount('tickets', 2);
    }

    public function test_a_ticket_generated_from_a_purchase_keeps_its_source_ids(): void
    {
        $item = $this->createTicketableItem('sourced-ticket');
        $inventory = Inventory::query()->create();
        $variant = $item->variants()->create(['inventory_id' => $inventory->id]);
        $purchase = $this->createPurchase($item, 1, $variant->id);

        $purchase->markAsPaid();

        $this->assertDatabaseHas('tickets', [
            'source_purchase_id' => $purchase->id,
            'source_catalog_item_id' => $item->id,
            'source_variant_id' => $variant->id,
        ]);
    }

    public function test_event_date_and_time_window_are_combined_in_the_same_and_group(): void
    {
        $item = $this->createTicketableItem('scheduled-meal');
        $eventDate = EventDate::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'date' => '2026-08-20',
            'time_start' => '09:00:00',
            'time_end' => '23:59:59',
        ]);
        $timeWindow = ValidityTime::query()->create([
            'type' => ValidityTimeType::TimeWindow,
            'start_time' => '22:00:00',
            'end_time' => '02:00:00',
        ]);
        $schedule = Attribute::query()->create([
            'tenant_codigo' => $this->tenant->codigo,
            'codigo' => 'schedule',
            'nombre' => 'Schedule',
            'type' => FieldType::Select,
        ]);
        $schedule->options()->create([
            'value' => 'night',
            'label' => '22:00 - 02:00',
            'validity_time_id' => $timeWindow->id,
        ]);
        $itemSchedule = $item->itemAttributes()->create([
            'attribute_id' => $schedule->id,
        ]);
        $inventory = Inventory::query()->create();
        $variant = $item->variants()->create([
            'event_date_id' => $eventDate->id,
            'inventory_id' => $inventory->id,
        ]);
        $variant->definitions()->create([
            'item_attribute_id' => $itemSchedule->id,
            'value' => 'night',
        ]);

        $tickets = $this->service->generate($item, $this->user, 2, $variant->id);

        $this->assertCount(2, $tickets);
        $this->assertTrue($tickets->every(fn ($ticket): bool => $ticket->resolvedValidityGroups()->count() === 1));
        $this->assertTrue($tickets->every(
            fn ($ticket): bool => $ticket->resolvedValidityGroups()->sole()->validityTimes
                ->pluck('id')
                ->sort()
                ->values()
                ->all() === collect([$eventDate->validity_time_id, $timeWindow->id])->sort()->values()->all()
        ));
        $this->assertSame(
            '2026-08-20 22:00:00',
            $tickets->first()->getEffectiveStartsAt()->format('Y-m-d H:i:s'),
        );
        $this->assertSame(
            '2026-08-20 23:59:59',
            $tickets->first()->getEffectiveExpiresAt()->format('Y-m-d H:i:s'),
        );
    }

    public function test_it_generates_one_ticket_per_unit_covering_all_selected_dates(): void
    {
        $item = $this->createTicketableItem('multi-date-pass');
        $dates = collect(['2026-08-20', '2026-08-21'])->map(fn (string $date) => EventDate::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'date' => $date,
            'time_start' => '00:00:00',
            'time_end' => '23:59:59',
        ]));
        $variant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create()->id,
        ]);
        $variant->eventDates()->sync($dates->pluck('id'));

        $tickets = $this->service->generate($item, $this->user, 2, $variant->id);
        $this->assertCount(2, $tickets);
        $this->assertTrue($tickets->every(fn ($ticket): bool => $ticket->resolvedValidityGroups()->count() === 2));
        $this->assertTrue($tickets->every(
            fn ($ticket): bool => $ticket->resolvedValidityGroups()->every(
                fn ($group): bool => $group->validityTimes->count() === 1
            )
        ));
        $this->assertEqualsCanonicalizing(
            $dates->pluck('validity_time_id')->all(),
            $tickets->flatMap(
                fn ($ticket) => $ticket->resolvedValidityGroups()
                    ->flatMap(fn ($group) => $group->validityTimes)
            )->pluck('id')->unique()->all(),
        );
        $this->assertTrue($tickets->every(
            fn ($ticket): bool => $ticket->name === 'Multi-date-pass (20/08/2026, 21/08/2026)'
        ));
        $this->assertTrue($tickets->every(
            fn ($ticket): bool => $ticket->resolvedValidityGroups()
                ->flatMap(fn ($group) => $group->validityTimes)
                ->map(fn (ValidityTime $validityTime): array => [
                    $validityTime->fixed_starts_at->format('Y-m-d H:i:s'),
                    $validityTime->fixed_expires_at->format('Y-m-d H:i:s'),
                ])
                ->all() === [
                    ['2026-08-20 00:00:00', '2026-08-20 23:59:59'],
                    ['2026-08-21 00:00:00', '2026-08-21 23:59:59'],
                ]
        ));
    }

    public function test_ticket_validity_is_resolved_from_soft_deleted_catalog_sources(): void
    {
        $item = $this->createTicketableItem('archived-ticket-source');
        $eventDate = EventDate::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'date' => '2026-07-21',
            'time_start' => '00:00:00',
            'time_end' => '23:59:59',
        ]);
        $variant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create()->id,
        ]);
        $variant->eventDates()->attach($eventDate);
        $ticket = $this->service->generate($item, $this->user, 1, $variant->id)->sole();

        app(CatalogService::class)->delete($item);
        $ticket = $ticket->fresh();

        $this->assertTrue($ticket->sourceCatalogItem->trashed());
        $this->assertTrue($ticket->sourceVariant->trashed());
        $this->assertTrue($ticket->isValid());
        $this->assertSame(
            '2026-07-21 23:59:59',
            $ticket->getEffectiveExpiresAt()->format('Y-m-d H:i:s'),
        );
    }

    public function test_common_schedule_is_anded_into_each_alternative_event_date_group(): void
    {
        $item = $this->createTicketableItem('multi-date-lunch');
        $dates = collect(['2026-08-20', '2026-08-21'])->map(fn (string $date) => EventDate::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'date' => $date,
            'time_start' => '09:00:00',
            'time_end' => '18:00:00',
        ]));
        $lunch = ValidityTime::query()->create([
            'type' => ValidityTimeType::TimeWindow,
            'start_time' => '12:00:00',
            'end_time' => '15:00:00',
        ]);
        $schedule = Attribute::query()->create([
            'tenant_codigo' => $this->tenant->codigo,
            'codigo' => 'schedule',
            'nombre' => 'Schedule',
            'type' => FieldType::Select,
        ]);
        $schedule->options()->create([
            'value' => 'lunch',
            'label' => 'Lunch',
            'validity_time_id' => $lunch->id,
        ]);
        $itemSchedule = $item->itemAttributes()->create(['attribute_id' => $schedule->id]);
        $variant = $item->variants()->create([
            'inventory_id' => Inventory::query()->create()->id,
        ]);
        $variant->eventDates()->sync($dates->pluck('id'));
        $variant->definitions()->create([
            'item_attribute_id' => $itemSchedule->id,
            'value' => 'lunch',
        ]);

        $ticket = $this->service->generate($item, $this->user, 1, $variant->id)->sole();
        $this->assertCount(2, $ticket->resolvedValidityGroups());
        $this->assertTrue($ticket->resolvedValidityGroups()->every(
            fn ($group): bool => $group->validityTimes->count() === 2
                && $group->validityTimes->contains($lunch)
        ));
        $this->assertEqualsCanonicalizing(
            $dates->pluck('validity_time_id')->all(),
            $ticket->resolvedValidityGroups()
                ->flatMap->validityTimes
                ->reject(fn (ValidityTime $validityTime): bool => $validityTime->is($lunch))
                ->pluck('id')
                ->all(),
        );
        $this->assertSame('2026-08-20 12:00:00', $ticket->getEffectiveStartsAt()->format('Y-m-d H:i:s'));
        $this->assertSame('2026-08-21 15:00:00', $ticket->getEffectiveExpiresAt()->format('Y-m-d H:i:s'));

        Carbon::setTestNow('2026-08-20 13:00:00');
        $this->assertTrue($ticket->isValid());

        Carbon::setTestNow('2026-08-20 16:00:00');
        $this->assertFalse($ticket->isValid());
        $this->assertFalse($ticket->is_expired);
    }

    public function test_marking_a_purchase_as_paid_ignores_items_without_tickets(): void
    {
        $item = $this->createTicketableItem('regular-product');
        $item->update(['has_tickets' => false]);
        $purchase = $this->createPurchase($item->fresh(), 1);

        $purchase->markAsPaid();

        $this->assertSame(Purchase::STATUS_PAID, $purchase->status);
        $this->assertDatabaseCount('tickets', 0);

        $this->actingAs($this->user, 'sanctum')
            ->getJson("/api/tenants/{$this->tenant->codigo}/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.tickets_count', 0)
            ->assertJsonPath('data.has_generated_tickets', false);
    }

    public function test_paid_status_is_confirmed_when_ticket_is_generated(): void
    {
        $item = $this->createTicketableItem('paid-ticket');
        $purchase = $this->createPurchase($item, 1);

        $purchase->markAsPaid();

        $this->assertSame(Purchase::STATUS_PAID, $purchase->fresh()->status);
        $this->assertDatabaseHas('tickets', [
            'source_catalog_item_id' => $item->id,
            'user_id' => $purchase->user_id,
        ]);
    }

    private function createTicketableItem(string $slug): CatalogItem
    {
        return CatalogItem::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'slug' => $slug,
            'nombre' => ucfirst($slug),
            'descripcion' => "Descripción de {$slug}",
            'precio' => 10,
            'has_tickets' => true,
        ]);
    }

    private function createBundle(string $slug): CatalogItem
    {
        return CatalogItem::query()->create([
            'tenant_code' => $this->tenant->codigo,
            'type' => CatalogItemType::Bundle,
            'inventory_policy' => null,
            'slug' => $slug,
            'nombre' => ucfirst($slug),
            'descripcion' => "Descripción de {$slug}",
            'precio' => 20,
        ]);
    }

    private function createPurchase(
        CatalogItem $catalogItem,
        int $quantity,
        ?int $sourceVariantId = null,
    ): Purchase {
        $purchase = Purchase::query()->create([
            'tenant_codigo' => $this->tenant->codigo,
            'user_id' => $this->user->id,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'payment_method' => 'transfer',
            'total' => 10 * $quantity,
        ]);

        $purchase->items()->create([
            'source_catalog_item_id' => $catalogItem->id,
            'source_variant_id' => $sourceVariantId,
            'image_attachment_id' => null,
            'nombre' => $catalogItem->nombre,
            'descripcion' => $catalogItem->descripcion,
            'slug' => $catalogItem->slug,
            'item_nombre' => $catalogItem->nombre,
            'variant_attributes' => [],
            'cantidad' => $quantity,
            'precio_unitario' => 10,
            'discount_total' => null,
            'tax_total' => null,
            'total' => 10 * $quantity,
        ]);

        return $purchase;
    }

    private function createTenant(): Tenant
    {
        $header = Attachment::query()->create([
            'path' => 'test/ticket-header.png',
            'filename' => 'header.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footer = Attachment::query()->create([
            'path' => 'test/ticket-footer.png',
            'filename' => 'footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        return Tenant::query()->create([
            'codigo' => 'ticket-tenant',
            'nombre' => 'Ticket Tenant',
            'dominio' => 'ticket.local',
            'primary_color' => '#000000',
            'secondary_color' => '#000000',
            'danger_color' => '#000000',
            'success_color' => '#000000',
            'header_bg_color' => '#000000',
            'footer_bg_color' => '#000000',
            'header_logo_id' => $header->id,
            'footer_logo_id' => $footer->id,
        ]);
    }
}
