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

const pathRegex = /^\/project\/[a-z0-9-]+\/?$/i;

export default async function (context: Context) {
	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}`);
	}
}