import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ url, locals }) => {
	const { session } = await locals.safeGetSession();

	// If already logged in, redirect to dashboard
	if (session) {
		throw redirect(303, '/dashboard');
	}

	// Handle URL-based error messages
	const errorCode = url.searchParams.get('error');
	let errorMessage: string | null = null;

	if (errorCode === 'no_profile') {
		errorMessage = 'Your account is not properly configured. Please contact support or try signing up again.';
	} else if (errorCode === 'expired') {
		errorMessage = 'Your session has expired. Please sign in again.';
	} else if (errorCode) {
		errorMessage = decodeURIComponent(errorCode);
	}

	return {
		redirectTo: url.searchParams.get('redirectTo') || '/dashboard',
		urlError: errorMessage
	};
};

export const actions: Actions = {
	default: async ({ request, locals, url }) => {
		const formData = await request.formData();
		const email = formData.get('email') as string;
		const password = formData.get('password') as string;
		const redirectTo = url.searchParams.get('redirectTo') || '/dashboard';

		if (!email || !password) {
			return fail(400, {
				error: 'Please enter your email and password',
				email
			});
		}

		const { data, error } = await locals.supabase.auth.signInWithPassword({
			email,
			password
		});

		if (error) {
			// Handle specific error cases
			if (error.message.includes('Invalid login credentials')) {
				return fail(400, {
					error: 'Invalid email or password. Please try again.',
					email
				});
			}

			if (error.message.includes('Email not confirmed')) {
				return fail(400, {
					error: 'Please verify your email address before signing in. Check your inbox for the verification link.',
					email
				});
			}

			return fail(400, {
				error: error.message,
				email
			});
		}

		// Check if member profile exists
		const { data: member } = await locals.supabase
			.from('members')
			.select('id')
			.eq('id', data.user.id)
			.single();

		if (!member) {
			// User exists in auth but not in members table - unusual situation
			// They may have been deleted or there was a signup issue
			await locals.supabase.auth.signOut();
			return fail(400, {
				error: 'Your account is not properly configured. Please contact support.',
				email
			});
		}

		throw redirect(303, redirectTo);
	}
};
