<?php

namespace Tests\Feature\Sale;

use App\Domains\Auth\Models\User;
use App\Domains\Authorization\Enums\RoleCode;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Events\PurchasePaid;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Models\WebsiteType;
use App\Domains\Ticket\Models\Ticket;
use Database\Seeders\AuthorizationSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class AdminAppSaleControllerTest extends TestCase
{
    use RefreshDatabase;

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

        $this->seed(AuthorizationSeeder::class);
        WebsiteType::query()->create(['codigo' => 'onticket', 'nombre' => 'OnTicket']);
    }

    public function test_sales_list_uses_purchase_item_snapshots_for_every_status(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'entrada-general',
            'nombre' => 'Entrada general',
            'precio' => '10000.00',
        ]);

        $createdCart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => 'checkout',
        ]);
        CartItem::query()->create([
            'cart_id' => $createdCart->id,
            'catalog_item_id' => $catalogItem->id,
            'cantidad' => 3,
        ]);
        $createdPurchase = Purchase::query()->create([
            'cart_id' => $createdCart->id,
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_CREATED,
            'total' => '30000.00',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $createdPurchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 3,
            'precio_unitario' => '10000.00',
            'total' => '30000.00',
        ]);

        $pendingCart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => 'checkout',
        ]);
        CartItem::query()->create([
            'cart_id' => $pendingCart->id,
            'catalog_item_id' => $catalogItem->id,
            'cantidad' => 4,
        ]);
        $pendingPurchase = Purchase::query()->create([
            'cart_id' => $pendingCart->id,
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'total' => '40000.00',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $pendingPurchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 4,
            'precio_unitario' => '10000.00',
            'total' => '40000.00',
        ]);

        $paidPurchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '20000.00',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $paidPurchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 2,
            'precio_unitario' => '10000.00',
            'total' => '20000.00',
        ]);

        $supersededPurchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_SUPERSEDED,
            'total' => '50000.00',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $supersededPurchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 5,
            'precio_unitario' => '10000.00',
            'total' => '50000.00',
        ]);

        $this->getJson('/api/v1/adminapp/tenant/sales?sort_by=id&sort_direction=asc')
            ->assertOk()
            ->assertJsonCount(3, 'data')
            ->assertJsonPath('data.0.id', $createdPurchase->id)
            ->assertJsonPath('data.0.quantity', 3)
            ->assertJsonPath('data.1.id', $pendingPurchase->id)
            ->assertJsonPath('data.1.quantity', 4)
            ->assertJsonPath('data.2.id', $paidPurchase->id)
            ->assertJsonPath('data.2.quantity', 2);

        $this->getJson('/api/v1/adminapp/tenant/sales?status='.Purchase::STATUS_SUPERSEDED)
            ->assertOk()
            ->assertJsonCount(0, 'data');
    }

    public function test_authentication_is_required_to_read_a_sale_detail(): void
    {
        $this->getJson('/api/v1/adminapp/tenant/sales/1')->assertUnauthorized();
    }

    public function test_pending_payment_filter_also_returns_purchases_in_review(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $pendingPurchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
        ]);
        $reviewPurchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_IN_REVIEW,
        ]);
        Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PAID,
        ]);

        $this->getJson('/api/v1/adminapp/tenant/sales?status=pending_payment&sort_by=id&sort_direction=asc')
            ->assertOk()
            ->assertJsonCount(2, 'data')
            ->assertJsonPath('data.0.id', $pendingPurchase->id)
            ->assertJsonPath('data.1.id', $reviewPurchase->id);
    }

    public function test_an_adminapp_user_can_read_a_sale_detail_from_its_tenant(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $purchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '40000.00',
            'nombre_apellido' => 'Ada Lovelace',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => 10,
            'nombre' => 'Comida',
            'item_nombre' => 'Comida',
            'variant_attributes' => [
                ['name' => 'Fecha', 'value' => ['2026-10-12']],
                ['name' => 'Servicio', 'value' => 'Almuerzo'],
            ],
            'cantidad' => 2,
            'precio_unitario' => '10000.00',
            'total' => '20000.00',
        ]);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.id', $purchase->id)
            ->assertJsonPath('data.items.0.product', 'Comida')
            ->assertJsonPath('data.items.0.event_dates.0', '2026-10-12')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '10000.00')
            ->assertJsonPath('data.items.0.total', '20000.00')
            ->assertJsonPath('data.total', '40000.00');
    }

    public function test_an_adminapp_user_can_read_purchase_item_snapshots_from_an_unconfirmed_sale(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'entrada-general',
            'nombre' => 'Entrada general',
            'descripcion' => 'Acceso general',
            'precio' => '12500.00',
        ]);
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => 'checkout',
        ]);
        $cartItem = CartItem::query()->create([
            'cart_id' => $cart->id,
            'catalog_item_id' => $catalogItem->id,
            'cantidad' => 2,
        ]);
        $purchase = Purchase::query()->create([
            'cart_id' => $cart->id,
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'total' => '25000.00',
        ]);
        $purchaseItem = PurchaseItem::query()->create([
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 2,
            'precio_unitario' => '12500.00',
            'total' => '25000.00',
        ]);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items.0.id', $purchaseItem->id)
            ->assertJsonPath('data.items.0.product', 'Entrada general')
            ->assertJsonPath('data.items.0.event_dates', [])
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '12500.00')
            ->assertJsonPath('data.items.0.total', '25000.00');
    }

    public function test_sales_list_quantity_always_comes_from_purchase_items(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'entrada-general',
            'nombre' => 'Entrada general',
            'descripcion' => 'Acceso general',
            'precio' => '12500.00',
        ]);
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => 'checkout',
        ]);
        CartItem::query()->create([
            'cart_id' => $cart->id,
            'catalog_item_id' => $catalogItem->id,
            'cantidad' => 3,
        ]);
        $purchase = Purchase::query()->create([
            'cart_id' => $cart->id,
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'total' => '37500.00',
        ]);
        $purchaseItem = PurchaseItem::query()->create([
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'nombre' => 'Entrada general',
            'item_nombre' => 'Entrada general',
            'cantidad' => 2,
            'precio_unitario' => '12500.00',
            'total' => '25000.00',
        ]);

        $this->getJson('/api/v1/adminapp/tenant/sales')
            ->assertOk()
            ->assertJsonPath('data.0.id', $purchase->id)
            ->assertJsonPath('data.0.quantity', 2);

        $purchaseItem->update([
            'cantidad' => 4,
            'total' => '50000.00',
        ]);

        $this->getJson('/api/v1/adminapp/tenant/sales')
            ->assertOk()
            ->assertJsonPath('data.0.quantity', 4);
    }

    public function test_an_adminapp_user_cannot_read_a_sale_from_another_tenant(): void
    {
        $tenant = $this->createTenant('acme');
        $otherTenant = $this->createTenant('other');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $foreignPurchase = Purchase::query()->create([
            'tenant_codigo' => $otherTenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '10000.00',
        ]);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$foreignPurchase->id}")
            ->assertNotFound();
    }

    public function test_an_adminapp_user_can_read_all_tickets_from_a_sale_in_its_tenant(): void
    {
        $tenant = $this->createTenant('acme');
        $admin = $this->createAdminAppUser($tenant);
        Sanctum::actingAs($admin);

        $purchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '20000.00',
        ]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'abono-general',
            'nombre' => 'Abono general',
            'descripcion' => 'Acceso general',
            'precio' => 20000,
            'has_tickets' => true,
        ]);
        $firstTicket = Ticket::query()->create([
            'tenant_code' => $tenant->codigo,
            'ticket' => '11111111-1111-4111-8111-111111111111',
            'source_purchase_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'user_id' => $admin->id,
        ]);
        $usedTicket = Ticket::query()->create([
            'tenant_code' => $tenant->codigo,
            'ticket' => '22222222-2222-4222-8222-222222222222',
            'source_purchase_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'used_at' => now()->subMinute(),
            'user_id' => $admin->id,
        ]);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/tickets")
            ->assertOk()
            ->assertExactJson([
                'data' => [
                    [
                        'product' => 'Abono general',
                        'id' => $firstTicket->id,
                        'expires_at' => null,
                        'status' => Ticket::STATUS_ACTIVE,
                    ],
                    [
                        'product' => 'Abono general',
                        'id' => $usedTicket->id,
                        'expires_at' => null,
                        'status' => Ticket::STATUS_USED,
                    ],
                ],
            ]);
    }

    public function test_an_adminapp_user_cannot_read_tickets_from_another_tenant_sale(): void
    {
        $tenant = $this->createTenant('acme');
        $otherTenant = $this->createTenant('other');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $foreignPurchase = Purchase::query()->create([
            'tenant_codigo' => $otherTenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '10000.00',
        ]);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$foreignPurchase->id}/tickets")
            ->assertNotFound();
    }

    public function test_an_adminapp_user_can_confirm_a_pending_sale(): void
    {
        Event::fake([PurchasePaid::class]);
        $tenant = $this->createTenant('acme');
        $admin = $this->createAdminAppUser($tenant);
        Sanctum::actingAs($admin);

        $inventory = Inventory::query()->create(['real_stock' => 10]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'confirmable-item',
            'nombre' => 'Confirmable item',
            'precio' => '10000.00',
        ]);
        $variant = Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ]);
        $purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
            'direct_items' => [[
                'catalog_item_id' => $catalogItem->id,
                'variant_id' => $variant->id,
                'cantidad' => 1,
            ]],
        ]);
        $purchase->update(['status' => Purchase::STATUS_PENDING_PAYMENT]);

        $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/confirm")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PAID);

        $this->assertSame(Purchase::STATUS_PAID, $purchase->fresh()->status);
        $this->assertDatabaseHas('value_changes', [
            'trackable_id' => $purchase->id,
            'attribute' => 'status',
            'old_value' => Purchase::STATUS_PENDING_PAYMENT,
            'new_value' => Purchase::STATUS_PAID,
            'user_id' => $admin->id,
        ]);
        Event::assertDispatchedTimes(PurchasePaid::class, 1);

        $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/confirm")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PAID);
        Event::assertDispatchedTimes(PurchasePaid::class, 1);
    }

    public function test_adminapp_cancellation_does_not_restore_the_source_cart(): void
    {
        $tenant = $this->createTenant('acme');
        $admin = $this->createAdminAppUser($tenant);
        Sanctum::actingAs($admin);

        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $admin->id,
            'status' => 'converted',
        ]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'entrada-general',
            'nombre' => 'Entrada general',
            'descripcion' => 'Acceso general',
            'precio' => '10000.00',
        ]);
        CartItem::query()->create([
            'cart_id' => $cart->id,
            'catalog_item_id' => $catalogItem->id,
            'cantidad' => 2,
        ]);
        $cart->delete();
        $purchase = Purchase::query()->create([
            'cart_id' => $cart->id,
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'total' => '10000.00',
        ]);
        PurchaseItem::query()->create([
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'item_nombre' => $catalogItem->nombre,
            'cantidad' => 2,
            'precio_unitario' => '10000.00',
            'total' => '20000.00',
        ]);

        $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED)
            ->assertJsonPath('data.quantity', 2);

        $this->assertSame(Purchase::STATUS_CANCELLED, $purchase->fresh()->status);
        $this->assertSoftDeleted('carritos', ['id' => $cart->id]);
        $this->assertSame('converted', Cart::withTrashed()->findOrFail($cart->id)->status);

        $this->getJson("/api/v1/adminapp/tenant/sales/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items.0.product', 'Entrada general')
            ->assertJsonPath('data.items.0.quantity', 2);
    }

    public function test_adminapp_can_cancel_a_purchase_in_review(): void
    {
        $tenant = $this->createTenant('acme');
        $admin = $this->createAdminAppUser($tenant);
        Sanctum::actingAs($admin);
        $inventory = Inventory::query()->create(['real_stock' => 10]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'slug' => 'review-item',
            'nombre' => 'Review item',
            'precio' => '10000.00',
        ]);
        $variant = Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ]);
        $purchase = app(CheckoutService::class)->startCheckout($tenant, $admin->id, [
            'direct_items' => [[
                'catalog_item_id' => $catalogItem->id,
                'variant_id' => $variant->id,
                'cantidad' => 2,
            ]],
        ]);
        $purchase->update(['status' => Purchase::STATUS_IN_REVIEW]);
        $sourceCartId = $purchase->cart_id;

        $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CANCELLED);

        $this->assertSoftDeleted('carritos', ['id' => $sourceCartId]);
        $this->assertDatabaseHas('stock_reservations', [
            'purchase_id' => $purchase->id,
            'status' => 'released',
        ]);
    }

    public function test_an_adminapp_user_cannot_change_a_sale_from_another_tenant(): void
    {
        $tenant = $this->createTenant('acme');
        $otherTenant = $this->createTenant('other');
        Sanctum::actingAs($this->createAdminAppUser($tenant));

        $foreignPurchase = Purchase::query()->create([
            'tenant_codigo' => $otherTenant->codigo,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'total' => '10000.00',
        ]);

        $this->postJson("/api/v1/adminapp/tenant/sales/{$foreignPurchase->id}/confirm")
            ->assertNotFound();
        $this->postJson("/api/v1/adminapp/tenant/sales/{$foreignPurchase->id}/cancel")
            ->assertNotFound();
    }

    public function test_a_paid_sale_cannot_be_cancelled_from_adminapp(): void
    {
        $tenant = $this->createTenant('acme');
        Sanctum::actingAs($this->createAdminAppUser($tenant));
        $purchase = Purchase::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'status' => Purchase::STATUS_PAID,
            'total' => '10000.00',
        ]);

        $this->postJson("/api/v1/adminapp/tenant/sales/{$purchase->id}/cancel")
            ->assertUnprocessable()
            ->assertJsonValidationErrors('purchase');
    }

    private function createTenant(string $code): Tenant
    {
        return Tenant::query()->create([
            'codigo' => $code,
            'nombre' => ucfirst($code),
            'dominio' => "{$code}.test",
            'website_type_code' => 'onticket',
        ]);
    }

    private function createAdminAppUser(Tenant $tenant): User
    {
        return User::factory()->create([
            'rol_codigo' => RoleCode::AdminApp->value,
            'tenant_codigo' => $tenant->codigo,
        ]);
    }
}
