import { beforeEach, describe, expect, it, vi } from 'vitest'

import {
  buildPlatformAuditBackfillRows,
  createLegacyAuditInsertValues,
  recordAudit,
  type LegacyAuditWrite,
} from '../audit'

describe('audit platform parity', () => {
  beforeEach(() => {
    vi.restoreAllMocks()
  })

  it('records an audit row through the platform module while preserving legacy columns in metadata', async () => {
    const returning = vi.fn().mockResolvedValue([{ id: 'audit-row-1' }])
    const values = vi.fn(() => ({ returning }))
    const insert = vi.fn(() => ({ values }))
    const db = { insert }

    const input: LegacyAuditWrite = {
      tenantId: '8f31466c-0919-4e30-9a40-b0f3fece9523',
      actorId: '1aaaf050-b4ca-40a4-905f-78e46efaf3fc',
      actorType: 'user',
      apiKeyId: '6c13bf8b-9c10-4bab-a90d-cafd35fb61fe',
      entityType: 'invoice',
      entityId: '2f346d2d-7f38-45cf-9414-c60f846e02c8',
      action: 'invoice.approved',
      changes: {
        status: ['pending', 'approved'],
        approver: [null, 'owner@example.com'],
      },
      requestId: 'req-123',
      ip: '203.0.113.10',
    }

    const result = await recordAudit(db as never, input)

    expect(result).toEqual({ logged: true, id: 'audit-row-1' })
    expect(insert).toHaveBeenCalledTimes(1)
    expect(values).toHaveBeenCalledWith(
      expect.objectContaining({
        tenantId: input.tenantId,
        actorId: input.actorId,
        actorType: input.actorType,
        action: input.action,
        entityType: input.entityType,
        entityId: input.entityId,
        ip: input.ip,
        metadata: {
          apiKeyId: input.apiKeyId,
          changes: input.changes,
          requestId: input.requestId,
        },
      }),
    )
  })

  it('maps legacy audit rows into module-compatible backfill rows', () => {
    const createdAt = new Date('2026-07-01T10:00:00.000Z')
    const rows = buildPlatformAuditBackfillRows([
      {
        id: 'audit-row-1',
        tenantId: '8f31466c-0919-4e30-9a40-b0f3fece9523',
        actorId: '1aaaf050-b4ca-40a4-905f-78e46efaf3fc',
        actorType: 'api_key',
        apiKeyId: '6c13bf8b-9c10-4bab-a90d-cafd35fb61fe',
        entityType: 'invoice',
        entityId: '2f346d2d-7f38-45cf-9414-c60f846e02c8',
        action: 'invoice.approved',
        changes: {
          status: ['pending', 'approved'],
        },
        requestId: 'req-123',
        ip: '203.0.113.10',
        createdAt,
      },
    ])

    expect(rows).toEqual([
      {
        id: 'audit-row-1',
        tenantId: '8f31466c-0919-4e30-9a40-b0f3fece9523',
        actorId: '1aaaf050-b4ca-40a4-905f-78e46efaf3fc',
        actorType: 'api_key',
        actorLabel: 'api_key:6c13bf8b-9c10-4bab-a90d-cafd35fb61fe',
        entityType: 'invoice',
        entityId: '2f346d2d-7f38-45cf-9414-c60f846e02c8',
        action: 'invoice.approved',
        metadata: {
          apiKeyId: '6c13bf8b-9c10-4bab-a90d-cafd35fb61fe',
          changes: {
            status: ['pending', 'approved'],
          },
          requestId: 'req-123',
        },
        ip: '203.0.113.10',
        createdAt,
      },
    ])
  })

  it('creates legacy insert values for unchanged query-layer call sites', () => {
    const values = createLegacyAuditInsertValues({
      tenantId: '8f31466c-0919-4e30-9a40-b0f3fece9523',
      actorId: null,
      actorType: 'system',
      entityType: 'job',
      entityId: 'daily-rollup',
      action: 'job.executed',
      metadata: {
        requestId: 'req-123',
        apiKeyId: 'api-key-1',
        changes: {
          status: ['pending', 'completed'],
        },
      },
      ip: null,
    })

    expect(values).toEqual({
      tenantId: '8f31466c-0919-4e30-9a40-b0f3fece9523',
      actorId: null,
      actorType: 'system',
      apiKeyId: 'api-key-1',
      entityType: 'job',
      entityId: 'daily-rollup',
      action: 'job.executed',
      changes: {
        status: ['pending', 'completed'],
      },
      requestId: 'req-123',
      ip: null,
    })
  })
})
