<?php

namespace Tests\Feature;

use App\Models\Outlet;
use App\Models\Product;
use App\Models\Register;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class SyncOfflineBatchTest extends TestCase
{
    use RefreshDatabase;

    public function test_sync_batch_is_idempotent_by_client_order_id(): void
    {
        $outlet = Outlet::query()->create(['name' => 'Outlet Sync', 'timezone' => 'Asia/Jakarta']);
        $register = Register::query()->create(['outlet_id' => $outlet->id, 'name' => 'Kasir 1']);
        $product = Product::query()->create([
            'outlet_id' => $outlet->id,
            'name' => 'Geprek',
            'sku' => 'GEP-1',
            'base_price' => 25000,
            'is_active' => true,
        ]);
        $user = User::factory()->create(['outlet_id' => $outlet->id, 'role' => 'cashier']);

        Sanctum::actingAs($user);

        $clientOrderId = (string) Str::uuid();
        $payload = [
            'orders' => [
                [
                    'client_order_id' => $clientOrderId,
                    'register_id' => $register->id,
                    'order_type' => 'takeaway',
                    'discount' => 0,
                    'items' => [
                        [
                            'product_id' => $product->id,
                            'qty' => 1,
                            'addon_ids' => [],
                        ],
                    ],
                    'payments' => [
                        ['method' => 'QRIS', 'amount' => 27750],
                    ],
                ],
            ],
        ];

        $this->postJson('/api/sync/orders', $payload)->assertOk();
        $this->postJson('/api/sync/orders', $payload)->assertOk();

        $this->assertDatabaseCount('orders', 1);
        $this->assertDatabaseHas('orders', ['client_order_id' => $clientOrderId]);
    }
}
