import { createClient } from "@supabase/supabase-js";
import { readFile } from "node:fs/promises";

const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
const userId = process.env.LEFTY_IMPORT_USER_ID;
const settingsFile = process.env.LEFTY_SETTINGS_FILE || "private-data/settings.json";
if (!url || !serviceRoleKey || !userId) {
  console.error("Missing NEXT_PUBLIC_SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY or LEFTY_IMPORT_USER_ID.");
  process.exit(1);
}

const settings = JSON.parse(await readFile(settingsFile, "utf8"));
const supabase = createClient(url, serviceRoleKey, { auth: { autoRefreshToken:false, persistSession:false } });
const profile = {
  id: userId,
  first_name: settings.profile?.firstName || "",
  monthly_net_income: Number(settings.profile?.monthlyIncome || 0),
  salary_day: settings.profile?.salaryDay || null,
  savings_target: Number(settings.profile?.savingsTarget || 0),
  safety_reserve: Number(settings.profile?.safetyReserve || 0),
  currency: "EUR",
};
const { error: profileError } = await supabase.from("profiles").upsert(profile, { onConflict: "id" });
if (profileError) throw profileError;

const month = settings.budgetMonth;
const budgetRows = (settings.budgets || []).map((b) => ({ user_id:userId, category_name:b.category, month, amount:Number(b.amount) }));
if (budgetRows.length) {
  const { error: budgetError } = await supabase.from("budgets").upsert(budgetRows, { onConflict:"user_id,category_name,month" });
  if (budgetError) throw budgetError;
}
console.log(`Profile and ${budgetRows.length} budgets updated.`);
