import { redirect, fail } from '@sveltejs/kit';
import type { Actions } from './$types';
import * as auth from '$lib/server/auth';

export const actions: Actions = {
	default: async ({ request, cookies }) => {
		const data = await request.formData();
		const email = data.get('email')?.toString();
		const password = data.get('password')?.toString();
		const firstName = data.get('firstName')?.toString();
		const lastName = data.get('lastName')?.toString();
		const anonymousId = data.get('anonymousId')?.toString();

		if (!email || !password || !anonymousId) {
			return fail(400, { error: 'Email, password, and anonymous ID are required' });
		}

		// Basic email validation
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			return fail(400, { error: 'Please enter a valid email address' });
		}

		if (password.length < 6) {
			return fail(400, { error: 'Password must be at least 6 characters' });
		}

		try {
			// Check if user already exists
			const existingUser = await auth.getUserByEmail(email);
			if (existingUser) {
				return fail(400, { error: 'An account with this email already exists' });
			}

			// Hash password
			const passwordHash = await auth.hashPassword(password);

			// Create user with anonymousId as the user ID
			const user = await auth.createUser(
				anonymousId,
				email,
				passwordHash,
				firstName || undefined,
				lastName || undefined
			);

			// Create session
			const sessionToken = auth.generateSessionToken();
			const session = await auth.createSession(sessionToken, user.id);
			auth.setSessionTokenCookie({ cookies }, sessionToken, session.expiresAt);

			return { success: true };
		} catch (error) {
			console.error('Sign up error:', error);
			
			// Check if it's a unique constraint error (user with this ID already exists)
			if (error instanceof Error && error.message.includes('UNIQUE constraint')) {
				return fail(400, { error: 'This account is already registered. Please sign in instead.' });
			}
			
			return fail(500, { error: 'An error occurred during account creation' });
		}
	}
};