import { Context } from "@nuxt/types/app";
import { RootState } from "~/store";
import fetchDefaultView from '~/assets/query/project/fetchDefaultView.gql';
import { parseSlug } from "~/src/helpers";

// Global middleware which is applied on every page
// and emposes various redirect conditions.

export default async function (context: Context) {
	
	const state: RootState = context.store.state;

	// --------------------------------------------------
	// Redirect to the installation page
	// --------------------------------------------------

	if(state.config.installing) {
		if(context.route.path.startsWith('/install')) {
			return;
		}
		
		context.redirect('/install');
	}

	// --------------------------------------------------
	// Require authentication when anonymnous is disabled
	// --------------------------------------------------

	if(!state.isAuthed && !state.config.allowAnonymous) {
		if(context.route.path.startsWith('/authenticate')) {
			return;
		}
	
		context.redirect('/authenticate');
	}

	// --------------------------------------------------
	// Require emails to be verified
	// --------------------------------------------------

	if(state.isAuthed && state.profile?.isVerified == false && state.config.verification) {
		if(context.route.path.startsWith('/authenticate/complete')) {
			return;
		}

		context.redirect('/authenticate/complete');
		return;
	}

	const pathRegex = /^\/project\/[a-z0-9-]+\/?$/i;
	const { fullPath } = context.route;

	if(pathRegex.test(fullPath)) {
		const projectId = fullPath.split('/')[2];
		const pid = parseSlug(projectId);

		// Assert project existence
		if(pid == undefined) {
			context.error({
				statusCode: 404,
				message: 'Project not found'
			});
			return;
		}

		// Fetch the default view
		const res = await context.$api.query(fetchDefaultView, {
			pid: pid
		});

		const project = res.project;

		if(!project) {
			context.error({
				statusCode: 404,
				message: 'Project not found'
			});
			return;
		}

		context.redirect(`/project/${projectId}/${project.defaultView}`);
	}
}