<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\Pelanggan;
use App\Models\StokAkhir;
use App\Models\Transaksi;
use App\Models\Notification;
use App\Livewire\User\ActiveOrders;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class CancelOrderTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_cancel_active_order_waiting_for_confirmation(): void
    {
        // 1. Create a user
        $user = User::create([
            'id_user' => 'USR1234',
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => 'password123',
            'role' => 'user',
            'phone' => '081234567890',
            'address' => 'Test Address',
        ]);

        // 2. Create customer details
        $pelanggan = Pelanggan::create([
            'customers_id' => 'USR1234',
            'name' => 'John Doe',
            'phone' => '081234567890',
            'address' => 'Test Address',
            'price_category' => 0,
        ]);

        // 3. Create a product with stock
        $product = StokAkhir::create([
            'id_produk' => 'P1111',
            'nama_produk' => 'Gas LPG 3kg',
            'jenis_barang' => 'LPG',
            'stok_isi' => 10,
            'stok_kosong' => 2,
            'total_aset' => 12,
        ]);

        // 4. Create a transaction (order) with status 'menunggu'
        $transaction = Transaksi::create([
            'id_transaksi' => 'TX202606280001',
            'customers_id' => 'USR1234',
            'id_produk' => 'P1111',
            'qty_beli_isi' => 2,
            'qty_tukar_kosong' => 2,
            'harga_satuan' => 20000,
            'ongkir' => 1000,
            'total_harga' => 41000,
            'metode_bayar' => 'COD',
            'nama_pengirim' => 'User',
            'tanggal_transaksi' => now()->toDateString(),
            'status' => 'menunggu',
        ]);

        // 5. Test Livewire cancellation
        Livewire::actingAs($user)
            ->test(ActiveOrders::class)
            ->call('cancelOrder', $transaction->id_transaksi)
            ->assertDispatched('swal-success');

        // 6. Assert database changes
        $this->assertDatabaseHas('transaksi', [
            'id_transaksi' => $transaction->id_transaksi,
            'status' => 'dibatalkan',
        ]);

        // Stock should be incremented back (10 + 2 = 12)
        $product->refresh();
        $this->assertEquals(12, $product->stok_isi);

        // Notification should be created
        $this->assertDatabaseHas('notifications', [
            'id_user' => 'USR1234',
            'id_transaksi' => $transaction->id_transaksi,
            'judul' => 'Pesanan Dibatalkan',
        ]);
    }
}
