import axios, { AxiosError } from "axios";
import { NextRequest, NextResponse } from "next/server";
import { DiscordAccount, prisma, PrismaClient } from "@repo/db";
import { getServerSession } from "../auth/[...nextauth]/auth";

export const GET = async (req: NextRequest) => {
	const session = await getServerSession();
	const code = req.nextUrl.searchParams.get("code");

	if (!session) {
		return NextResponse.redirect(`${process.env.NEXTAUTH_URL}/login`);
	}

	if (
		!process.env.DISCORD_OAUTH_CLIENT_ID ||
		!process.env.DISCORD_OAUTH_SECRET ||
		!process.env.DISCORD_REDIRECT_URL ||
		!code
	) {
		return NextResponse.json(
			{
				error: "Discord OAuth not configured",
			},
			{
				status: 500,
			},
		);
	}

	const params = new URLSearchParams({
		client_id: process.env.DISCORD_OAUTH_CLIENT_ID,
		client_secret: process.env.DISCORD_OAUTH_SECRET,
		redirect_uri: process.env.DISCORD_REDIRECT_URL,
		grant_type: "authorization_code",
		code,
	});

	const headers = {
		"Content-Type": "application/x-www-form-urlencoded",
	};
	try {
		const { data: authData } = await axios.post("https://discord.com/api/oauth2/token", params, {
			headers,
		});

		const { data: discordUser } = await axios.get("https://discord.com/api/users/@me", {
			headers: {
				Authorization: `Bearer ${authData.access_token}`,
			},
		});

		const discordObject = {
			userId: session.user.id,
			accessToken: authData.access_token,
			refreshToken: authData.refresh_token,
			discordId: discordUser.id,
			email: discordUser.email,
			avatar: discordUser.avatar,
			username: discordUser.username,
			globalName: discordUser.global_name,
			verified: discordUser.verified,
			tokenType: authData.token_type,
		} as DiscordAccount;

		await prisma.discordAccount.upsert({
			where: { discordId: discordUser.id },
			update: discordObject, // Updates if found
			create: discordObject, // Creates if not found
		});
		return NextResponse.redirect(`${process.env.NEXT_PUBLIC_HUB_URL}/settings`);
	} catch (error: any) {
		console.error(error);
		return NextResponse.json(
			{
				error: "Couldn't connect to Discord",
			},
			{
				status: 500,
			},
		);
	}
};
