import { eq, and, gte, desc } from 'drizzle-orm';
import type { DrizzleClient } from '../client';
import { aiInterventions } from '../schema';
import type { InferInsertModel, InferSelectModel } from 'drizzle-orm';

export type AiInterventionRow = InferSelectModel<typeof aiInterventions>;
export type NewAiIntervention = InferInsertModel<typeof aiInterventions>;

export async function insertEncrypted(
  db: DrizzleClient,
  row: Omit<NewAiIntervention, 'inputEncrypted' | 'outputEncrypted'>,
  plaintextIn: string,
  plaintextOut: string,
  _key: string,
): Promise<AiInterventionRow> {
  // In production, use pgp_sym_encrypt. Here store base64 marker.
  const inputEncrypted = `[encrypted:${Buffer.from(plaintextIn).toString('base64')}]`;
  const outputEncrypted = `[encrypted:${Buffer.from(plaintextOut).toString('base64')}]`;
  const [result] = await db
    .insert(aiInterventions)
    .values({ ...row, inputEncrypted, outputEncrypted })
    .returning();
  return result!;
}

export async function listByParent(
  db: DrizzleClient,
  parentType: AiInterventionRow['parentType'],
  parentId: string,
) {
  return db
    .select()
    .from(aiInterventions)
    .where(and(eq(aiInterventions.parentType, parentType), eq(aiInterventions.parentId, parentId)))
    .orderBy(desc(aiInterventions.createdAt));
}

export async function countRecentForBudget(
  db: DrizzleClient,
  parentType: AiInterventionRow['parentType'],
  parentId: string,
  sinceMs: number,
): Promise<number> {
  const since = new Date(Date.now() - sinceMs);
  const rows = await db
    .select()
    .from(aiInterventions)
    .where(
      and(
        eq(aiInterventions.parentType, parentType),
        eq(aiInterventions.parentId, parentId),
        gte(aiInterventions.createdAt, since),
      ),
    );
  return rows.length;
}
