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

export const load: PageServerLoad = async ({ url, locals }) => {
	// Check for token in URL (from email link via /auth/verify redirect)
	const token = url.searchParams.get('token');
	const type = url.searchParams.get('type');
	const error = url.searchParams.get('error');

	// If there's an error from a previous attempt, show it
	if (error) {
		return { error };
	}

	// If there's a token, we need to verify it to establish a session
	if (token) {
		try {
			// For recovery/invite tokens, verify the OTP
			const otpType = type === 'invite' ? 'invite' : 'recovery';

			const { data, error: verifyError } = await locals.supabase.auth.verifyOtp({
				token_hash: token,
				type: otpType
			});

			if (verifyError) {
				console.error('Token verification error:', verifyError);
				// Token invalid or expired
				throw redirect(
					303,
					`/forgot-password?error=${encodeURIComponent(verifyError.message || 'Invalid or expired reset link. Please request a new one.')}`
				);
			}

			if (data.session) {
				// Session established - user can now reset password
				return {
					isInvite: type === 'invite',
					email: data.user?.email
				};
			}
		} catch (e) {
			// Check if it's a redirect (which is expected)
			if (e && typeof e === 'object' && 'status' in e) {
				throw e;
			}
			console.error('Verification error:', e);
			throw redirect(303, '/forgot-password?error=expired');
		}
	}

	// No token - check if user has an existing session (from successful verification)
	const { session } = await locals.safeGetSession();

	if (!session) {
		// No session and no token - invalid access
		throw redirect(303, '/forgot-password?error=expired');
	}

	return {
		email: session.user?.email
	};
};

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

		// Validation
		if (!password || password.length < 8) {
			return fail(400, {
				error: 'Password must be at least 8 characters long'
			});
		}

		if (password !== confirmPassword) {
			return fail(400, {
				error: 'Passwords do not match'
			});
		}

		// Check if user has a session
		const { session } = await locals.safeGetSession();
		if (!session) {
			return fail(401, {
				error: 'Session expired. Please request a new password reset link.'
			});
		}

		// Update the password
		const { error } = await locals.supabase.auth.updateUser({
			password
		});

		if (error) {
			console.error('Password update error:', error);
			return fail(400, {
				error: error.message
			});
		}

		// Sign out after password change so they can sign in fresh
		await locals.supabase.auth.signOut();

		return {
			success: 'Your password has been set successfully! You can now sign in with your new password.'
		};
	}
};
