<?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\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Purchase\Services\CheckoutService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;

class PurchaseCatalogItemTest extends TestCase
{
    use RefreshDatabase;

    public function test_checkout_persists_catalog_identity_without_polymorphism(): void
    {
        Storage::fake('s3');
        Storage::disk('s3')->buildTemporaryUrlsUsing(
            fn (string $path): string => "https://snapshots.test/{$path}",
        );

        $tenant = $this->createTenant();
        $user = User::factory()->create();
        $inventory = Inventory::query()->create(['real_stock' => 10]);
        $catalogItem = CatalogItem::query()->create([
            'tenant_code' => $tenant->codigo,
            'inventory_id' => $inventory->id,
            'slug' => 'checkout-item',
            'nombre' => 'Checkout item',
            'descripcion' => 'Original description',
            'precio' => 25,
        ]);
        $productImage = $this->createAttachment('checkout-item');
        Storage::disk('s3')->put($productImage->path, 'original-image');
        $catalogItem->attachments()->attach($productImage->id, ['orden' => 0]);
        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $user->id,
            'status' => 'active',
        ]);
        $cart->addItem($catalogItem->id, null, 2);

        $service = app(CheckoutService::class);
        $purchase = $service->startCheckout($tenant, $user->id, [
            'cart_id' => $cart->id,
            'dni' => '12345678',
            'telefono' => '123456789',
            'nombre_apellido' => 'Test User',
            'email' => 'test@example.com',
        ]);
        $service->confirmPurchase($purchase);

        $this->assertTrue(Schema::hasColumns('compra_items', [
            'source_catalog_item_id',
            'source_variant_id',
            'image_attachment_id',
            'nombre',
            'descripcion',
            'slug',
            'item_nombre',
            'variant_attributes',
        ]));
        $this->assertFalse(Schema::hasColumn('compra_items', 'catalog_item_id'));
        $this->assertFalse(Schema::hasColumn('compra_items', 'variant_id'));
        $this->assertFalse(Schema::hasColumn('compra_items', 'buyable_type'));
        $this->assertFalse(Schema::hasColumn('compra_items', 'buyable_id'));
        $this->assertFalse(Schema::hasColumn('compra_items', 'reservation_status'));
        $this->assertDatabaseHas('compra_items', [
            'compra_id' => $purchase->id,
            'source_catalog_item_id' => $catalogItem->id,
            'source_variant_id' => null,
            'image_attachment_id' => $purchase->items()->value('image_attachment_id'),
            'nombre' => 'Checkout item',
            'descripcion' => 'Original description',
            'slug' => 'checkout-item',
            'item_nombre' => 'Checkout item',
            'cantidad' => 2,
            'precio_unitario' => '25.00',
            'total' => '50.00',
        ]);
        $purchaseItem = $purchase->items()->with('imageAttachment')->firstOrFail();
        $this->assertNotNull($purchaseItem->imageAttachment);
        $this->assertSame($productImage->id, $purchaseItem->image_attachment_id);
        $this->assertSame('original-image', Storage::disk('s3')->get($purchaseItem->imageAttachment->path));
        $this->assertSame($productImage->path, $purchaseItem->imageAttachment->path);
        $this->assertDatabaseCount('attachments', 3);
        $catalogItem->update([
            'nombre' => 'Changed catalog item',
            'descripcion' => 'Changed description',
        ]);
        $catalogItem->delete();

        $purchaseItem->refresh();
        $this->assertSame('Checkout item', $purchaseItem->nombre);
        $this->assertSame('Original description', $purchaseItem->descripcion);
        $this->assertDatabaseHas('compra_items', ['id' => $purchaseItem->id]);
        $this->actingAs($user, 'sanctum')
            ->getJson("/api/tenants/{$tenant->codigo}/compras/{$purchase->id}")
            ->assertOk()
            ->assertJsonPath('data.items.0.source_catalog_item_id', $catalogItem->id)
            ->assertJsonPath('data.items.0.item_details.nombre', 'Checkout item')
            ->assertJsonPath('data.items.0.item_details.descripcion', 'Original description')
            ->assertJsonMissingPath('data.items.0.product')
            ->assertJsonMissingPath('data.items.0.variant');
        $this->assertDatabaseHas('inventories', [
            'id' => $inventory->id,
            'real_stock' => 8,
            'reserved_stock' => 0,
            'sold_units' => 2,
        ]);
    }

    private function createTenant(): Tenant
    {
        $headerLogo = $this->createAttachment('purchase-header');
        $footerLogo = $this->createAttachment('purchase-footer');

        return Tenant::query()->create([
            'codigo' => 'purchase-catalog',
            'nombre' => 'Purchase Catalog',
            'dominio' => 'purchase-catalog.local',
            'primary_color' => '#000000',
            'secondary_color' => '#000000',
            'danger_color' => '#000000',
            'success_color' => '#000000',
            'header_bg_color' => '#000000',
            'footer_bg_color' => '#000000',
            'header_logo_id' => $headerLogo->id,
            'footer_logo_id' => $footerLogo->id,
        ]);
    }

    private function createAttachment(string $name): Attachment
    {
        return Attachment::query()->create([
            'path' => "test/{$name}.png",
            'filename' => "{$name}.png",
            'type' => AttachmentType::Image,
            'mime_type' => 'image/png',
            'extension' => 'png',
            'size' => 14,
        ]);
    }
}
