import { describe, expect, it } from 'vitest'
import { postIssue } from '../post-issue.js'
import { postReceipt } from '../post-receipt.js'
import { getCogs, getMovements } from './cogs-movements.js'
import {
  AVG_ITEM_ID,
  LOCATION_A,
  NOW,
  TENANT_ID,
  freshDb,
  seedItem,
  seedLocation,
} from '../test-helpers.js'

describe('cogs and movement reads', () => {
  it('reads cogs totals and filtered movements from stock_movement', async () => {
    const db = await freshDb()
    await seedLocation(db, LOCATION_A)
    await seedItem(db, AVG_ITEM_ID, 'weighted_average')

    await postReceipt(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 4,
      unitCost: 6,
      occurredAt: new Date('2026-07-04T10:00:00.000Z'),
    })
    await postIssue(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
      qty: 2,
      holderRef: 'issue-cogs',
      occurredAt: NOW,
      method: 'weighted_average',
      allowNegative: false,
    })

    const cogs = await getCogs(db, {
      tenantId: TENANT_ID,
      from: new Date('2026-07-04T00:00:00.000Z'),
      to: new Date('2026-07-05T00:00:00.000Z'),
      itemId: AVG_ITEM_ID,
    })
    const movements = await getMovements(db, {
      tenantId: TENANT_ID,
      itemId: AVG_ITEM_ID,
      locationId: LOCATION_A,
    })

    expect(cogs.total).toBe('12')
    expect(movements).toHaveLength(2)
    expect(movements[1]?.kind).toBe('issue')
  })
})
