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

describe('setModuleStateAdmin', () => {
  it('writes tuple-shaped audit changes for admin overrides', async () => {
    const insertCalls: Array<{ table: unknown; values: Record<string, unknown> }> = []

    const tx = {
      insert: vi.fn((table: unknown) => ({
        values: vi.fn((values: Record<string, unknown>) => {
          insertCalls.push({ table, values })
          return {
            onConflictDoUpdate: vi.fn().mockResolvedValue(undefined),
          }
        }),
      })),
    }

    const db = {
      transaction: vi.fn(async (fn: (txArg: typeof tx) => Promise<unknown>) => fn(tx)),
    }

    const { setModuleStateAdmin } = await import('../../src/queries/tenant-modules')

    await setModuleStateAdmin(
      db as never,
      '00000000-0000-4000-8000-000000000001',
      'crm',
      false,
      '00000000-0000-4000-8000-000000000002',
      'Support forced this module off',
    )

    expect(insertCalls).toHaveLength(2)
    expect(insertCalls[1]?.values).toMatchObject({
      tenantId: '00000000-0000-4000-8000-000000000001',
      actorId: '00000000-0000-4000-8000-000000000002',
      actorType: 'admin',
      entityType: 'tenant_module',
      entityId: '00000000-0000-4000-8000-000000000001',
      action: 'tenant_module.admin_override',
      changes: {
        moduleId: [null, 'crm'],
        enabled: [null, false],
        reason: [null, 'Support forced this module off'],
        overrideBySystemAdmin: [null, true],
      },
    })
  })
})
