import { dev } from '$app/environment';
import { fail, redirect } from '@sveltejs/kit';
import { authenticate } from '$lib/auth';

const COOKIE_NAME = 'session';

/** @type {import('./$types').Actions} */
export const actions = {
	login: async ({ request, cookies }) => {
		const data = await request.formData();
		const user = data.get('user');
		const password = data.get('password');

		const token = authenticate(user, password);

		if (!token) return fail(400, { user, incorrect: true });

		cookies.set(COOKIE_NAME, token, {
			path: '/',
			httpOnly: true,
			sameSite: 'strict',
			secure: !dev
		});
		throw redirect(303, '/');
	},
	logout: async (event) => {
		event.cookies.delete(COOKIE_NAME);
		event.locals.user = null;
		return { success: true };
	}
};
