import { describe, expect, it } from 'vitest'
import type { Querier } from '@platform-modules/db'
import { logAudit } from './log-audit.js'
import type { AuditSchema } from './schema.js'
import { countAudit, createTestDb, getAuditById } from './test-fixture.js'

describe('logAudit', () => {
  it('inserts a row and returns logged:true with id', async () => {
    const db = await createTestDb()

    const result = await logAudit(db, {
      actorId: 'user-1',
      actorType: 'user',
      actorLabel: 'Alice',
      action: 'update',
      entityType: 'deal',
      entityId: 'deal-1',
      tenantId: 'tenant-a',
      metadata: { field: 'status' },
      ip: '127.0.0.1',
    })

    expect(result.logged).toBe(true)
    expect(result.id).toBeTypeOf('string')
    expect(await countAudit(db)).toBe(1)

    const row = await getAuditById(db, result.id!)
    expect(row?.action).toBe('update')
    expect(row?.entityId).toBe('deal-1')
  })

  it('never throws when the insert rejects', async () => {
    const failingDb = {
      insert: () => ({
        values: () => ({
          returning: () => Promise.reject(new Error('db down')),
        }),
      }),
    } as unknown as Querier<AuditSchema>

    await expect(
      logAudit(failingDb, {
        action: 'delete',
        entityType: 'deal',
        entityId: 'deal-2',
      }),
    ).resolves.toEqual({
      logged: false,
      error: expect.any(Error),
    })
  })

  it('accepts nullable actorId and roundtrips metadata jsonb', async () => {
    const db = await createTestDb()

    const result = await logAudit(db, {
      actorId: null,
      actorType: 'system',
      action: 'cron.run',
      entityType: 'job',
      entityId: 'job-1',
      metadata: { nested: { ok: true }, count: 3 },
    })

    expect(result.logged).toBe(true)
    const row = await getAuditById(db, result.id!)
    expect(row?.actorId).toBeNull()
    expect(row?.metadata).toEqual({ nested: { ok: true }, count: 3 })
  })
})
