<?php

namespace Tests\Feature\Purchase;

use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Auth\Models\User;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Enums\InventoryPolicy;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Str;
use Tests\TestCase;

class StorePurchaseTest extends TestCase
{
    use RefreshDatabase;

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

        Queue::fake();
    }

    public function test_it_creates_a_purchase_from_cart_id_without_persisting_items_yet(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $category = Category::query()->create([
            'tenant_code' => 'sonder',
            'nombre' => 'Test Category',
        ]);

        $inventory = Inventory::query()->create(['real_stock' => 10]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => 'sonder',
            'category_id' => $category->id,
            'slug' => 'test-product',
            'nombre' => 'Test Product',
            'descripcion' => 'Test',
            'precio' => '50.00',
        ]);

        $variant = Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ]);

        $cartResponse = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $catalogItem->id,
                'variant_id' => $variant->id,
                'cantidad' => 2,
            ])
            ->assertOk();

        $cartId = $cartResponse->json('data.id');

        $this->assertDatabaseHas('carritos', [
            'id' => $cartId,
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $response = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cartId,
                'dni' => '987654321',
                'telefono' => '+54 9 341 555-4321',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ]);

        $response->assertCreated();
        $response->assertJsonPath('data.cart_id', $cartId);
        $response->assertJsonPath('data.dni', '987654321');
        $response->assertJsonPath('data.telefono', '+54 9 341 555-4321');
        $response->assertJsonPath('data.nombre_apellido', 'Juan Perez');
        $response->assertJsonPath('data.email', 'juan.perez@example.com');
        $response->assertJsonPath('data.tenant_codigo', 'sonder');
        $response->assertJsonPath('data.status', Purchase::STATUS_CREATED);
        $response->assertJsonPath('data.items_source', null);
        $response->assertJsonPath('data.items', []);
        $response->assertJsonPath('data.subtotal', '100.00');
        $response->assertJsonPath('data.total', '100.00');

        $purchaseId = $response->json('data.id');

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'cart_id' => $cartId,
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'dni' => '987654321',
            'telefono' => '+54 9 341 555-4321',
            'nombre_apellido' => 'Juan Perez',
            'email' => 'juan.perez@example.com',
            'status' => Purchase::STATUS_CREATED,
            'total' => 100,
        ]);
        $this->assertDatabaseMissing('compra_items', [
            'compra_id' => $purchaseId,
        ]);
        $this->assertDatabaseHas('carritos', [
            'id' => $cartId,
            'status' => 'active',
            'user_id' => $user->id,
        ]);
        $this->assertDatabaseHas('carrito_items', [
            'cart_id' => $cartId,
            'catalog_item_id' => $catalogItem->id,
            'variant_id' => $variant->id,
            'cantidad' => 2,
        ]);
        $this->assertDatabaseHas('inventories', [
            'id' => $inventory->id,
            'real_stock' => 10,
            'reserved_stock' => 2,
        ]);
    }

    public function test_it_moves_a_created_purchase_to_pending_payment_when_finalized(): void
    {
        $tenant = $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $cartId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 2,
            ])
            ->assertOk()
            ->json('data.id');

        $purchaseId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cartId,
                'dni' => '987654321',
                'telefono' => '+54 9 341 555-4321',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertCreated()
            ->json('data.id');

        Purchase::query()
            ->whereKey($purchaseId)
            ->update([
                'payment_method' => 'transfer',
            ]);

        $this->actingAs($user, 'sanctum')
            ->postJson("/api/tenants/sonder/compras/{$purchaseId}/complete")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT);

        $this->assertDatabaseHas('compras', [
            'id' => $purchaseId,
            'status' => Purchase::STATUS_PENDING_PAYMENT,
            'payment_method' => 'transfer',
        ]);
    }

    public function test_purchase_detail_uses_cart_items_for_created_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_CREATED)
            ->assertJsonPath('data.items_source', 'cart')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.product.id', $variant->catalogItem->id)
            ->assertJsonPath('data.items.0.product.nombre', $variant->catalogItem->nombre)
            ->assertJsonPath('data.items.0.product.slug', $variant->catalogItem->slug)
            ->assertJsonPath('data.items.0.product.imagen', null)
            ->assertJsonPath('data.items.0.variant.id', $variant->id)
            ->assertJsonPath('data.items.0.variant.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_detail_uses_cart_items_for_pending_payment_purchase(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update([
            'payment_method' => 'transfer',
        ]);

        app(CheckoutService::class)->completePurchase($purchase);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PENDING_PAYMENT)
            ->assertJsonPath('data.items_source', 'cart')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.product.imagen', null)
            ->assertJsonPath('data.items.0.variant.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_detail_uses_purchase_items_for_paid_purchase_even_without_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->update([
            'payment_method' => 'transfer',
        ]);

        $checkoutService = app(CheckoutService::class);
        $purchase = $checkoutService->completePurchase($purchase);
        $checkoutService->confirmPurchase($purchase);
        $purchase->refresh()->markAsPaid();

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 8,
            'reserved_stock' => 0,
            'sold_units' => 2,
        ]);

        $this->assertSoftDeleted('carritos', [
            'id' => $purchase->cart_id,
        ]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.status', Purchase::STATUS_PAID)
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 2)
            ->assertJsonPath('data.items.0.unit_price', '50.00')
            ->assertJsonPath('data.items.0.line_total', '100.00')
            ->assertJsonPath('data.items.0.source_catalog_item_id', $variant->catalog_item_id)
            ->assertJsonPath('data.items.0.source_variant_id', $variant->id)
            ->assertJsonPath('data.items.0.item_details.imagen', null)
            ->assertJsonPath('data.items.0.item_details.attributes', [])
            ->assertJsonPath('data.subtotal', '100.00')
            ->assertJsonPath('data.total', '100.00');
    }

    public function test_purchase_detail_prefers_purchase_items_when_both_sources_exist(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $purchase->items()->create([
            'source_catalog_item_id' => $variant->catalog_item_id,
            'source_variant_id' => $variant->id,
            'nombre' => $variant->catalogItem->nombre,
            'descripcion' => $variant->catalogItem->descripcion,
            'slug' => $variant->catalogItem->slug,
            'item_nombre' => $variant->getName(),
            'variant_attributes' => [],
            'cantidad' => 1,
            'precio_unitario' => '50.00',
            'discount_total' => null,
            'tax_total' => null,
            'total' => '50.00',
        ]);

        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/sonder/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items_source', 'purchase')
            ->assertJsonCount(1, 'data.items')
            ->assertJsonPath('data.items.0.quantity', 1)
            ->assertJsonPath('data.items.0.line_total', '50.00')
            ->assertJsonPath('data.subtotal', '50.00')
            ->assertJsonPath('data.total', '50.00');
    }

    public function test_purchase_index_returns_empty_items_without_loaded_relations(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create([
            'email' => 'buyer@example.com',
        ]);
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');
        $this->createCheckoutPurchase($user, 'sonder', $variant, 2);

        $this->actingAs($user, 'sanctum')
            ->getJson('/api/tenants/sonder/compras?status=created')
            ->assertOk()
            ->assertJsonCount(1, 'data')
            ->assertJsonPath('data.0.items_source', null)
            ->assertJsonPath('data.0.items', [])
            ->assertJsonPath('data.0.total', '100.00');
    }

    public function test_it_rejects_a_cart_from_another_user(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $owner = User::factory()->create();
        $attacker = User::factory()->create();
        $variant = $this->createVariantForTenant('sonder', 10, '50.00');

        $cartId = $this->actingAs($owner, 'sanctum')
            ->postJson('/api/tenants/sonder/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 1,
            ])
            ->assertOk()
            ->json('data.id');

        $this->actingAs($attacker, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cartId,
                'dni' => '12345678',
                'telefono' => '+54 9 341 555-1111',
                'nombre_apellido' => 'Intruso',
                'email' => 'intruso@example.com',
            ])
            ->assertNotFound();
    }

    public function test_it_rejects_a_cart_from_another_tenant(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $this->createTenant('globex', 'Globex', 'globex.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant('globex', 10, '50.00');

        $cartId = $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/globex/cart/items', [
                'catalog_item_id' => $variant->catalog_item_id,
                'variant_id' => $variant->id,
                'cantidad' => 1,
            ])
            ->assertOk()
            ->json('data.id');

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cartId,
                'dni' => '12345678',
                'telefono' => '+54 9 341 555-1111',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertNotFound();
    }

    public function test_it_rejects_an_empty_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $cart = Cart::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cart->id,
                'dni' => '12345678',
                'telefono' => '+54 9 341 555-1111',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['cart_id']);
    }

    public function test_it_rejects_a_converted_cart(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $cart = Cart::query()->create([
            'tenant_codigo' => 'sonder',
            'user_id' => $user->id,
            'status' => 'converted',
        ]);

        $this->actingAs($user, 'sanctum')
            ->postJson('/api/tenants/sonder/compras', [
                'cart_id' => $cart->id,
                'dni' => '12345678',
                'telefono' => '+54 9 341 555-1111',
                'nombre_apellido' => 'Juan Perez',
                'email' => 'juan.perez@example.com',
            ])
            ->assertUnprocessable()
            ->assertJsonValidationErrors(['cart_id']);
    }

    public function test_it_confirms_unlimited_inventory_without_reducing_real_stock_and_is_idempotent(): void
    {
        $this->createTenant('sonder', 'Sonder', 'sonder.com.ar');
        $user = User::factory()->create();
        $variant = $this->createVariantForTenant(
            'sonder',
            0,
            '50.00',
            'unlimited',
            InventoryPolicy::Unlimited,
        );
        $purchase = $this->createCheckoutPurchase($user, 'sonder', $variant, 25);
        $purchase->update(['payment_method' => 'transfer']);

        $checkoutService = app(CheckoutService::class);
        $purchase = $checkoutService->completePurchase($purchase);
        $checkoutService->confirmPurchase($purchase);
        $checkoutService->confirmPurchase($purchase);

        $this->assertDatabaseHas('inventories', [
            'id' => $variant->inventory_id,
            'real_stock' => 0,
            'reserved_stock' => 0,
            'sold_units' => 25,
        ]);
        $this->assertDatabaseCount('compra_items', 1);
    }

    protected function createVariantForTenant(
        string $tenantCode,
        int $stock,
        string $price,
        string $slugPrefix = 'shirt',
        InventoryPolicy $inventoryPolicy = InventoryPolicy::Tracked,
    ): Variant {
        $tenant = Tenant::query()->where('codigo', $tenantCode)->first();
        if (! $tenant) {
            $this->createTenant($tenantCode, ucfirst($tenantCode), "{$tenantCode}.com");
        }

        $category = Category::query()->create([
            'tenant_code' => $tenantCode,
            'nombre' => "{$slugPrefix} category {$tenantCode}",
        ]);

        $inventory = Inventory::query()->create(['real_stock' => $stock]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenantCode,
            'category_id' => $category->id,
            'slug' => "{$slugPrefix}-{$tenantCode}-".CatalogItem::query()->count(),
            'nombre' => ucfirst($slugPrefix)." {$tenantCode}",
            'descripcion' => 'Test product',
            'precio' => $price,
            'inventory_policy' => $inventoryPolicy,
        ]);

        return Variant::query()->create([
            'catalog_item_id' => $catalogItem->id,
            'inventory_id' => $inventory->id,
        ])->load(['catalogItem', 'inventory']);
    }

    protected function createCheckoutPurchase(
        User $user,
        string $tenantCode,
        Variant $variant,
        int $quantity,
    ): Purchase {
        $tenant = Tenant::query()->where('codigo', $tenantCode)->firstOrFail();
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenantCode,
            'user_id' => $user->id,
            'status' => 'active',
        ]);

        $cart->addItem($variant->catalog_item_id, $variant->id, $quantity);

        return app(CheckoutService::class)->startCheckout($tenant, $user->id, [
            'cart_id' => $cart->id,
            'dni' => '987654321',
            'telefono' => '+54 9 341 555-4321',
            'nombre_apellido' => 'Juan Perez',
            'email' => 'juan.perez@example.com',
        ]);
    }

    protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
    {
        $hdrKey = (string) Str::uuid();
        $ftrKey = (string) Str::uuid();

        $headerAttachment = Attachment::create([
            'key' => $hdrKey,
            'path' => 'tenants/'.$hdrKey.'.png',
            'filename' => 'logo_header.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);
        $footerAttachment = Attachment::create([
            'key' => $ftrKey,
            'path' => 'tenants/'.$ftrKey.'.png',
            'filename' => 'logo_footer.png',
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
        ]);

        return Tenant::create([
            'codigo' => $codigo,
            'nombre' => $nombre,
            'dominio' => $dominio,
            'primary_color' => '#111111',
            'secondary_color' => '#222222',
            'danger_color' => '#333333',
            'success_color' => '#28a745',
            'header_bg_color' => '#444444',
            'footer_bg_color' => '#444444',
            'header_logo_id' => $headerAttachment->id,
            'footer_logo_id' => $footerAttachment->id,
        ]);
    }
}
