import { command, form, getRequestEvent, query } from '$app/server';
import { loginSchema, signupSchema } from '$lib/schema/auth';
import { BACKEND_API_URL } from '$lib/server/config';
import { invalid, redirect } from '@sveltejs/kit';

export const login = form(loginSchema, async (data, issue) => {
	const { cookies, locals } = getRequestEvent();

	// Create URL-encoded form data
	const formData = new URLSearchParams();
	formData.append('email', data.email);
	formData.append('password', data.password);

	const response = await fetch(`${BACKEND_API_URL}/access/login`, {
		method: 'POST',
		body: formData,
		headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
	});

	if (!response.ok) {
		if (response.status === 401) {
			invalid(issue.email('Invalid login credentials'));
		} else {
			const message = await response.text();
			console.error('Unknown error: ', message);
			invalid(issue.email('An unknown error occurred'));
		}
	}

	const token = await response.json();

	cookies.set('authToken', token.access_token, {
		path: '/',
		httpOnly: true,
		secure: true,
		sameSite: 'strict',
		maxAge: 60 * 60 * 24 * 7 // 1 week
	});

	redirect(303, '/');
});

export const signup = form(signupSchema, async (data, issue) => {
	const response = await fetch(`${BACKEND_API_URL}/access/signup`, {
		method: 'POST',
		body: JSON.stringify(data),
		headers: { 'Content-Type': 'application/json' }
	});

	if (!response.ok) {
		if (response.status == 409) {
			invalid(issue.email('Email is already in use by another account'));
		} else {
			const message = await response.text();
			console.error('Unknown error: ', message);
			invalid(issue.email('An unknown error occurred'));
		}
	}
});

export const logout = command(async () => {
	const { cookies } = getRequestEvent();

	cookies.delete('authToken', {
		path: '/'
	});
});

export const getUser = query(async () => {
	const { locals } = getRequestEvent();
	if (!locals.user) {
		redirect(307, '/login');
	}
	return locals.user;
});
