import { prisma } from "@repo/db";

export interface OldUser {
	firstname: string;
	publicId: string;
	badges: string[];
	lastname: string;
	email: string;
	password: string;
	settings: {
		privacyHideLastnameInNickname?: boolean;
		notifyRoomID?: string;
	};
	discord?: {
		profile: {
			id: string;
			username: string;
			global_name: string;
			avatar: string;
			email: string;
			verified: boolean;
		};
		tokens: {
			refresh_token: string;
			scope: string;
		};
	};
}

export const createNewUserFromOld = async (oldUser: OldUser) => {
	const newUser = await prisma.user.create({
		data: {
			email: oldUser.email,
			password: oldUser.password,
			migratedFromV1: true,
			firstname: oldUser.firstname,
			lastname: oldUser.lastname,
			publicId: oldUser.publicId,
			badges: [
				...oldUser.badges
					.map((badge) => {
						switch (badge) {
							case "day-1-member":
								return "DAY1";
							case "d-1":
								return "D1";
							case "p-1":
								return "P1";
							default:
								return null;
						}
					})
					.filter((badge) => badge !== null),
				"V1Veteran",
			],
		},
	});
	if (oldUser.discord) {
		await prisma.discordAccount.create({
			data: {
				tokenType: "Bearer",
				refreshToken: oldUser.discord.tokens.refresh_token,
				discordId: oldUser.discord.profile.id,
				userId: newUser.id,
				username: oldUser.discord.profile.username,
				globalName: oldUser.discord.profile.global_name,
				avatar: oldUser.discord.profile.avatar,
				email: oldUser.discord.profile.email,
				verified: oldUser.discord.profile.verified,
			},
		});
	}
	return newUser;
};
