import { serverSupabaseServiceRole } from "../../utils/useSupabase";
import { deleteUserUrgeLogs } from "../../db/urge";
import { deleteUserSosSessions } from "../../db/sosSession";
import { deleteUserStreaks } from "../../db/streak";
import { deleteUserPosts } from "../../db/community";
import { deleteAllUserCustomDomains } from "../../db/domains";
import {
  deleteUserTrustedContacts,
  deleteUserCoachSessions,
} from "../../db/user";
import { deleteProfile } from "../../db/profile";

export default defineEventHandler(async (event) => {
  const user = await requireUser(event);
  const supabase = serverSupabaseServiceRole(event);
  const userId = user.id;

  // Delete all user data (DSGVO Art. 17)
  await Promise.all([
    deleteUserUrgeLogs(userId),
    deleteUserSosSessions(userId),
    deleteUserStreaks(userId),
    deleteUserPosts(userId),
    deleteAllUserCustomDomains(userId),
    deleteUserTrustedContacts(userId),
    deleteUserCoachSessions(userId),
  ]);

  // Profil zuletzt löschen (FK-Abhängigkeiten sind bereits entfernt)
  await deleteProfile(userId).catch(() => {});

  // Auth-User löschen (bleibt Supabase)
  await supabase.auth.admin.deleteUser(userId);

  return { success: true };
});
