import { sql } from 'drizzle-orm'
import { describe, expect, it } from 'vitest'
import { postIssue } from './post-issue.js'
import { postReceipt } from './post-receipt.js'
import {
  AVG_ITEM_ID,
  LOCATION_A,
  NOW,
  TENANT_ID,
  firstRows,
  freshDb,
  seedItem,
  seedLocation,
} from './test-helpers.js'

describe('postReceipt', () => {
  it('posts a db-backed receipt and is idempotent on holderRef replay', async () => {
    const db = await freshDb()
    await seedLocation(db, LOCATION_A)
    await seedItem(db, AVG_ITEM_ID, 'weighted_average')

    const first = await postReceipt(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 3,
      unitCost: 9,
      holderRef: 'receipt-1',
      occurredAt: NOW,
    })
    const replay = await postReceipt(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 3,
      unitCost: 9,
      holderRef: 'receipt-1',
      occurredAt: NOW,
    })

    expect(replay.movement.id).toBe(first.movement.id)
    const rows = firstRows(await db.execute(sql`
      SELECT COUNT(*)::int AS count
      FROM stock_movement
      WHERE tenant_id = ${TENANT_ID}::uuid
        AND item_id = ${AVG_ITEM_ID}::uuid
        AND location_id = ${LOCATION_A}::uuid
    `))
    expect(Number(rows[0]?.count ?? 0)).toBe(1)
  })

  it('backfills pending_cost issues with auditable true-up adjustments', async () => {
    const db = await freshDb()
    await seedLocation(db, LOCATION_A)
    await seedItem(db, AVG_ITEM_ID, 'weighted_average')

    await postIssue(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 2,
      holderRef: 'issue-pending',
      occurredAt: new Date('2026-07-04T11:00:00.000Z'),
      method: 'weighted_average',
      allowNegative: true,
    })

    const receipt = await postReceipt(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 2,
      unitCost: 7,
      holderRef: 'receipt-2',
      occurredAt: NOW,
    })

    const rows = firstRows(await db.execute(sql`
      SELECT kind, qty_delta, cogs_amount, pending_cost, holder_ref
      FROM stock_movement
      WHERE tenant_id = ${TENANT_ID}::uuid
        AND item_id = ${AVG_ITEM_ID}::uuid
        AND location_id = ${LOCATION_A}::uuid
      ORDER BY occurred_at ASC, created_at ASC
    `))
    expect(rows).toHaveLength(3)
    expect(rows[0]?.pending_cost).toBe(true)
    expect(rows[2]?.kind).toBe('adjust')
    expect(Number(rows[2]?.qty_delta ?? 0)).toBe(0)
    expect(Number(rows[2]?.cogs_amount ?? 0)).toBe(14)
    expect(String(rows[2]?.holder_ref ?? '')).toContain(`issue-pending:trueup:${receipt.movement.id}`)
  })
})
