import { createHash } from "node:crypto";
import type { ContentType, TextLang } from "../../types.js";
import { withTransaction, ensureInvestigation, now } from "../../db.js";

export async function ingestText(
  entityId: string,
  text: string,
  investigation: string,
  textType: ContentType = "post",
  lang?: TextLang,
  publishedAt?: string,
  notes?: string,
): Promise<string> {
  const contentId =
    "text_" + createHash("sha256").update(text).digest("hex").slice(0, 16);

  await withTransaction(async (client) => {
    await ensureInvestigation(client, investigation);
    await client.query(
      `INSERT INTO content(id, investigation_id, entity_id, type, text,
                           text_lang, published_at, collected_at, raw_json)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
       ON CONFLICT (id) DO NOTHING`,
      [
        contentId,
        investigation,
        entityId,
        textType,
        text,
        lang ?? null,
        publishedAt ?? null,
        now(),
        JSON.stringify({ notes: notes ?? null }),
      ],
    );
  });

  console.log(`Text saved: ${contentId}`);
  return contentId;
}
