import { Context } from "@nuxt/types/app";
import { RootState } from "~/store";
import verifyAccount from "~/assets/query/profile/verifyAccount.gql";

// Middlewhich which only allows authenticated users
// to view a page, even when anonymous mode is active.

export default async function (context: Context) {

	const state: RootState = context.store.state;

	if(!state.isAuthed) {
		if(context.route.path.startsWith('/authenticate/complete') || 
			!context.route.path.startsWith('/authenticate')
		)
			context.redirect('/authenticate');
			
	} else if(state.isAuthed && context.route.path.startsWith('/authenticate/complete')) {
		if(state.profile?.isVerified) {
			context.redirect('/');
			return;
		}

		const code = context.route.query.code;

		if(code !== undefined) {
			const res = await context.$api.query(verifyAccount, {
				code: code
			});

			context.redirect('/?verified=' + res.verifyAccount);
		}
	}
}