"use server";

import { ValidAuthProvider } from "@/auth/AuthProvider";
import {
  AuthState,
  getAuthState,
  getRegisteringUser,
  getUser
} from "@/auth/auth";
import prisma from "@/prisma";

async function unlinkDiscord(id: string) {
  await prisma.discordAuth.delete({
    where: {
      id
    }
  });
}

async function unlinkGitHub(id: string) {
  await prisma.gitHubAuth.delete({
    where: {
      id
    }
  });
}

async function deleteUser(id: number) {
  await prisma.authTicket.deleteMany({
    where: {
      userId: id
    }
  });

  await prisma.user.delete({
    where: {
      id
    }
  });
}
export default async function unlink(provider?: ValidAuthProvider) {
  const authState = await getAuthState();

  if (authState == AuthState.Registering) {
    const registeringUser = (await getRegisteringUser())!;
    if (registeringUser.discordAuth !== null)
      await unlinkDiscord(registeringUser.discordAuth.id);

    if (registeringUser.githubAuth !== null)
      await unlinkGitHub(registeringUser.githubAuth.id);

    await deleteUser(registeringUser.id);

    return;
  }

  const user = await getUser();
  if (user == null) return;
  switch (provider) {
    case "Discord":
      const discord = await user.getDiscord();
      if (discord == null) return;
      await unlinkDiscord(await discord.getId());
      break;

    case "GitHub":
      const github = await user.getGitHub();
      if (github == null) return;
      await unlinkGitHub(await github.getId());
      break;
  }
}
