import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { withTransaction, ensureInvestigation, now } from "../../db.js";

export async function ingestProfile(
  filePath: string,
  investigation: string,
): Promise<void> {
  const raw = await readFile(resolve(filePath), "utf-8");
  const data = JSON.parse(raw) as Record<string, unknown>;

  const uid = String(data.id ?? data.uid ?? data.entity_id ?? "");
  if (!uid) {
    console.error("Cannot determine entity ID from profile JSON");
    return;
  }

  await withTransaction(async (client) => {
    await ensureInvestigation(client, investigation);
    await client.query(
      `INSERT INTO entities(id, investigation_id, type, name, url, platform,
                            country, created_at, confidence, is_sock,
                            notes, raw_json, collected_at)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)
       ON CONFLICT (id) DO UPDATE SET
           name         = EXCLUDED.name,
           country      = EXCLUDED.country,
           raw_json     = EXCLUDED.raw_json,
           collected_at = EXCLUDED.collected_at`,
      [
        uid,
        investigation,
        (data.type as string) ?? "profile",
        (data.name as string) ?? null,
        (data.url as string) ??
          `https://www.facebook.com/profile.php?id=${uid}`,
        "facebook",
        (data.location as string) ?? (data.country as string) ?? null,
        (data.created as string) ?? (data.created_at as string) ?? null,
        (data.confidence as number) ?? 70,
        Boolean(data.is_sock),
        (data.notes as string) ?? null,
        JSON.stringify(data),
        now(),
      ],
    );
  });

  console.log(`Profile saved: ${uid}`);
}
