import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { checkRateLimit } from '$lib/server/rate-limit';

export const load: PageServerLoad = async () => {
	return {};
};

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

		if (!email || !email.includes('@')) {
			return fail(400, {
				error: 'Please enter a valid email address',
				email
			});
		}

		// Rate limit password reset attempts by email
		const rateLimitKey = `forgot-password:${email}`;
		const rateCheck = checkRateLimit(rateLimitKey, 3, 15 * 60 * 1000); // 3 attempts per 15 min
		if (!rateCheck.allowed) {
			const retryMinutes = Math.ceil((rateCheck.retryAfterMs || 0) / 60000);
			return fail(429, {
				error: `Too many reset attempts. Please try again in ${retryMinutes} minute${retryMinutes !== 1 ? 's' : ''}.`,
				email
			});
		}

		const { error } = await locals.supabase.auth.resetPasswordForEmail(email, {
			redirectTo: `${url.origin}/auth/reset-password`
		});

		if (error) {
			// Don't reveal if email exists or not for security
			console.error('Password reset error:', error);
		}

		// Always show success message (don't reveal if email exists)
		return {
			success: 'If an account exists with this email, you will receive a password reset link shortly.'
		};
	}
};
