<?php

namespace Tests\Feature;

use App\Models\Product;
use App\Models\User;
use App\Models\Warehouse;
use App\Models\WarehouseStock;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class SaleOperatorFilterTest extends TestCase
{
    use RefreshDatabase;

    private function createSaleForUser(User $user, Warehouse $warehouse, Product $product, string $orderNo): void
    {
        $this->actingAs($user, 'sanctum')->postJson('/api/sales', [
            'order_no'     => $orderNo,
            'channel'      => 'tokopedia',
            'warehouse_id' => $warehouse->id,
            'items' => [
                ['product_id' => $product->id, 'qty' => 1, 'price' => 10000],
            ],
        ])->assertStatus(201);
    }

    public function test_operators_endpoint_returns_only_users_who_have_sales(): void
    {
        $operatorWithSale    = User::factory()->create(['name' => 'Budi']);
        $operatorWithoutSale = User::factory()->create(['name' => 'Ani']);
        $warehouse = Warehouse::create(['code' => 'WH1', 'name' => 'Gudang Utama']);
        $product   = Product::create(['sku' => 'SKU-001', 'name' => 'Produk Tes', 'sell_price' => 10000]);
        WarehouseStock::create([
            'warehouse_id'  => $warehouse->id,
            'product_id'    => $product->id,
            'current_stock' => 100,
            'min_stock'     => 5,
        ]);

        $this->createSaleForUser($operatorWithSale, $warehouse, $product, 'ORD-OP-1');

        $response = $this->actingAs($operatorWithSale, 'sanctum')->getJson('/api/sales/operators');

        $response->assertStatus(200);
        $names = collect($response->json())->pluck('name');
        $this->assertTrue($names->contains('Budi'));
        $this->assertFalse($names->contains('Ani'));
    }

    public function test_index_filters_sales_by_user_id(): void
    {
        $operatorA = User::factory()->create(['name' => 'Operator A']);
        $operatorB = User::factory()->create(['name' => 'Operator B']);
        $warehouse = Warehouse::create(['code' => 'WH1', 'name' => 'Gudang Utama']);
        $product   = Product::create(['sku' => 'SKU-001', 'name' => 'Produk Tes', 'sell_price' => 10000]);
        WarehouseStock::create([
            'warehouse_id'  => $warehouse->id,
            'product_id'    => $product->id,
            'current_stock' => 100,
            'min_stock'     => 5,
        ]);

        $this->createSaleForUser($operatorA, $warehouse, $product, 'ORD-A-1');
        $this->createSaleForUser($operatorB, $warehouse, $product, 'ORD-B-1');

        $response = $this->actingAs($operatorA, 'sanctum')->getJson("/api/sales?user_id={$operatorA->id}");

        $response->assertStatus(200);
        $orderNumbers = collect($response->json('data'))->pluck('order_no');
        $this->assertTrue($orderNumbers->contains('ORD-A-1'));
        $this->assertFalse($orderNumbers->contains('ORD-B-1'));
    }
}
