/**
 * Admin audit log query helpers.
 *
 * All mutations to the `admin_actions` table go through this module.
 * adminTargetTypeEnum = DEAL|VENDOR|REVIEW|USER|PURCHASE|KB_ARTICLE|SETTING|OUTBOX_EVENT
 * adminActionEnum = APPROVE|REJECT|FREEZE|UNFREEZE|BAN|REMOVE_REVIEW|RESTORE_REVIEW|
 * ADD_QUANTITY|GRANT_ADMIN|REVOKE_ADMIN|REQUEST_REFUND|RESEND_RECEIPT|
 * KB_CREATE|KB_UPDATE|KB_DELETE|SETTING_UPDATE|OUTBOX_RETRY
 */

import type { DrizzleClient } from '../client.js';
import { adminActions } from '../schema.js';
import type { adminTargetTypeEnum, adminActionEnum } from '../schema.js';

type TargetType = (typeof adminTargetTypeEnum.enumValues)[number];
type Action = (typeof adminActionEnum.enumValues)[number];

export type AdminActionInput = {
  /** Null when action was taken by an AI agent. */
  adminId: string | null;
  targetType: TargetType;
  /** UUID of the entity being acted upon. For SETTING changes, use the adminId as self-referential id. */
  targetId: string;
  action: Action;
  /** Optional free-text note or JSON-encoded op metadata. */
  note?: string | null;
};

/**
 * Insert one immutable audit-log row into admin_actions.
 * Does not return; audit rows are write-only from the application layer.
 */
export async function recordAdminAction(db: DrizzleClient, input: AdminActionInput): Promise<void> {
  await db.insert(adminActions).values({
    adminId: input.adminId,
    targetType: input.targetType,
    targetId: input.targetId,
    action: input.action,
    note: input.note ?? null,
  });
}
