<?php

use App\Models\Order;
use App\Models\Product;
use App\Models\Shop;
use App\Models\User;

it('requires selecting a tracked variant before adding a product to cart', function () {
    $user = User::factory()->create();

    $shop = Shop::create([
        'name' => 'Variant Shop',
        'brand_color' => '#123456',
        'created_by' => $user->id,
    ]);

    $product = Product::create([
        'shop_id' => $shop->id,
        'product_title' => 'Variant Tee',
        'price' => 1200,
        'stock' => 8,
        'sku' => 'VT-001',
        'attributes' => [
            '_variant_inventory' => [
                ['label' => 'Black', 'stock' => 5],
                ['label' => 'White', 'stock' => 3],
            ],
        ],
        'created_by' => $user->id,
    ]);

    $this->withHeader('Accept', 'application/json')
        ->post(route('storefront.cart.add', $product), [
            'quantity' => 1,
        ])
        ->assertStatus(422)
        ->assertJson([
            'error' => 'Please select an available product variant.',
        ]);
});

it('decrements selected variant stock and records it on the order item during checkout', function () {
    $user = User::factory()->create();

    $shop = Shop::create([
        'name' => 'Variant Shop',
        'brand_color' => '#123456',
        'created_by' => $user->id,
    ]);

    $product = Product::create([
        'shop_id' => $shop->id,
        'product_title' => 'Variant Tee',
        'price' => 1200,
        'stock' => 8,
        'sku' => 'VT-002',
        'attributes' => [
            '_variant_inventory' => [
                ['label' => 'Black', 'stock' => 5],
                ['label' => 'White', 'stock' => 3],
            ],
        ],
        'created_by' => $user->id,
    ]);

    $this->withHeader('Accept', 'application/json')
        ->post(route('storefront.cart.add', $product), [
            'quantity' => 2,
            'variant_label' => 'Black',
        ])
        ->assertOk();

    $this->post(route('storefront.checkout.cod'), [
        'customer_name' => 'Rahman',
        'phone' => '01700000000',
        'address' => 'Dhaka',
        'notes' => 'Variant order',
    ])->assertRedirect(route('storefront.home'));

    $product->refresh();
    $variants = $product->variantInventory();
    $blackVariant = collect($variants)->firstWhere('label', 'Black');

    expect($product->stock)->toBe(6)
        ->and($blackVariant['stock'])->toBe(3);

    $order = Order::query()->with('items')->sole();
    $item = $order->items->sole();

    expect($item->variant_label)->toBe('Black')
        ->and($item->quantity)->toBe(2)
        ->and((float) $item->line_total)->toBe(2400.0);
});
