import type { CurrentUser } from '../env';
import type { DbUserRow } from './schema';

export function mapUser(row: DbUserRow): CurrentUser {
  return {
    id: row.id,
    username: row.username,
    email: row.email,
    displayName: row.display_name,
    avatarKey: row.avatar_key,
    bio: row.bio || '',
    url: row.url || '',
    role: row.role,
    status: row.status
  };
}

export async function audit(
  db: D1Database,
  input: {
    actorId?: string | null;
    action: string;
    target?: string | null;
    detail?: unknown;
    ip?: string | null;
    createdAt: number;
  }
): Promise<void> {
  await db
    .prepare(
      `INSERT INTO wm_audit_log(actor_id, action, target, detail, ip, created_at)
       VALUES (?, ?, ?, ?, ?, ?)`
    )
    .bind(
      input.actorId || null,
      input.action,
      input.target || null,
      input.detail === undefined ? null : JSON.stringify(input.detail),
      input.ip || null,
      input.createdAt
    )
    .run();
}

export async function first<T>(statement: D1PreparedStatement): Promise<T | null> {
  return (await statement.first<T>()) || null;
}

export async function all<T>(statement: D1PreparedStatement): Promise<T[]> {
  const result = await statement.all<T>();
  return result.results || [];
}
