import type { Kysely } from 'kysely'
import type { DB } from '../../db/schema.js'

export type AuditAction = 'INSERT' | 'UPDATE' | 'DELETE'

export class AuditService {
  constructor(
    private readonly kysely: Kysely<DB>,
    private readonly userId: string | null
  ) {}

  async onInsert(table: string, recordId: string, data?: Record<string, unknown>) {
    await this.write(table, recordId, 'INSERT', data)
  }

  async onUpdate(table: string, recordId: string, data: Record<string, unknown>) {
    await this.write(table, recordId, 'UPDATE', data)
  }

  async onDelete(table: string, recordId: string) {
    await this.write(table, recordId, 'DELETE')
  }

  private async write(
    table: string,
    recordId: string,
    action: AuditAction,
    data?: Record<string, unknown>
  ) {
    await this.kysely
      .insertInto('auditLog')
      .values({
        tableName: table,
        recordId,
        action,
        userId: this.userId,
        changedFields: data == null ? null : (JSON.stringify(data) as any),
      } as any)
      .execute()
  }
}
