import { test, expect, APIRequestContext } from "@playwright/test"
import { ApiSeeder, newApiContext, Warehouse, Item, Vendor } from "../support/api"
import { StockAdjustmentNewPage } from "../pages/StockPages"

// Stock adjustment flow (Backend/ERPCore/Controllers/StockAdjustmentsController.cs,
// Frontend app/dashboard/stock/adjustments/new): posts immediately, no draft state
// (Backend/ERPCore/Dtos/Stock/AdjustmentDtos.cs - QtyDelta is a signed base-UOM delta).
test.describe("Stock adjustments", () => {
  let api: APIRequestContext
  let seeder: ApiSeeder
  let warehouse: Warehouse
  let vendor: Vendor
  let item: Item

  test.beforeAll(async () => {
    api = await newApiContext()
    seeder = new ApiSeeder(api)
    warehouse = await seeder.firstWarehouse()
    vendor = await seeder.createVendor()
    item = await seeder.createItem({ namePrefix: "Adjustment Test Item" })

    await seeder.receiveStock({
      warehouseId: warehouse.warehouseId,
      vendorId: vendor.vendorId,
      itemId: item.itemId,

      qty: 20,
      unitCost: 30,
    })
  })

  test.afterAll(async () => {
    await api.dispose()
  })

  test("positive adjustment increases on-hand and shows the posted doc number", async ({ page }) => {
    const before = await seeder.stockOnHand(item.itemId, warehouse.warehouseId)

    const newPage = new StockAdjustmentNewPage(page)
    await newPage.goto()
    await newPage.fill({ warehouse: warehouse.name, reasonCode: "System Correction", item: item.name, qtyDelta: 5 })
    await newPage.submit()

    await newPage.expectPosted()

    const after = await seeder.stockOnHand(item.itemId, warehouse.warehouseId)
    expect(after.onHand).toBeCloseTo(before.onHand + 5, 4)
  })

  test("negative adjustment decreases on-hand", async ({ page }) => {
    const before = await seeder.stockOnHand(item.itemId, warehouse.warehouseId)

    const newPage = new StockAdjustmentNewPage(page)
    await newPage.goto()
    await newPage.fill({ warehouse: warehouse.name, reasonCode: "Damage", item: item.name, qtyDelta: -3 })
    await newPage.submit()

    await newPage.expectPosted()

    const after = await seeder.stockOnHand(item.itemId, warehouse.warehouseId)
    expect(after.onHand).toBeCloseTo(before.onHand - 3, 4)
  })
})
