import { 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 anonymousId = data.get('anonymousId')?.toString();

		if (!email || !password) {
			return fail(400, { error: 'Email and password 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 {
			// Get user by email
			const user = await auth.getUserByEmail(email);
			if (!user || !user.passwordHash) {
				return fail(400, { error: 'Invalid email or password' });
			}

			// Verify password
			const isValidPassword = await auth.verifyPassword(password, user.passwordHash);
			if (!isValidPassword) {
				return fail(400, { error: 'Invalid email or password' });
			}

			// Migrate anonymous stats if different anonymous ID
			await auth.migrateAnonymousStats(anonymousId, user.id);

			// 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 in error:', error);
			return fail(500, { error: 'An error occurred during sign in' });
		}
	}
};