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 async function POST(request: Request) {
  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 new Response(null, { status: 200 });
  }

  const user = await getUser();
  if (user == null) return new Response(null, { status: 401 });

  const { searchParams } = new URL(request.url);
  const provider = searchParams.get("provider");
  switch (provider) {
    case "discord":
      const discord = await user.getDiscord();
      if (discord == null) return new Response(null, { status: 400 });
      await unlinkDiscord(await discord.getId());
      break;

    case "github":
      const github = await user.getGitHub();
      if (github == null) return new Response(null, { status: 400 });
      await unlinkGitHub(await github.getId());
      break;

    default:
      return new Response(null, { status: 400 });
  }

  return new Response(null, { status: 200 });
}
