import type { DatabaseSync } from "node:sqlite";
import type { ComplaintHistoryEntry } from "./types.js";

interface LedgerRow {
  content: string;
  sender_id: string | null;
  direction: string;
  timestamp: number;
}

export function fetchContext(
  db: DatabaseSync,
  channel: string,
  accountId: string,
  chatId: string,
  limit: number,
): ComplaintHistoryEntry[] {
  const rawRows = db
    .prepare(
      `SELECT content, sender_id, direction, timestamp
       FROM messages
       WHERE channel = ? AND account_id = ? AND chat_id = ?
       ORDER BY timestamp DESC
       LIMIT ?`,
    )
    .all(channel, accountId, chatId, limit) as Array<Record<string, unknown>>;
  const rows: LedgerRow[] = rawRows.map((r) => ({
    content: String(r.content ?? ""),
    sender_id: r.sender_id == null ? null : String(r.sender_id),
    direction: String(r.direction ?? "in"),
    timestamp: Number(r.timestamp ?? 0),
  }));
  return rows.reverse().map((r) => ({
    role: r.direction === "out" ? "agent" : "user",
    content: r.content,
    senderId: r.sender_id ?? undefined,
    ts: r.timestamp,
  }));
}
