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

export const load: PageServerLoad = async () => {
	// Check if any users exist in the system
	const { count, error } = await supabaseAdmin
		.from('members')
		.select('*', { count: 'exact', head: true });

	if (error) {
		console.error('Error checking for existing users:', error);
		// If we can't check, assume setup is needed (will fail gracefully later)
		return { needsSetup: true };
	}

	// If users already exist, redirect to login
	if (count && count > 0) {
		throw redirect(303, '/login');
	}

	return { needsSetup: true };
};

export const actions: Actions = {
	default: async ({ request, url }) => {
		// Double-check that no users exist (prevent race conditions)
		const { count: existingCount } = await supabaseAdmin
			.from('members')
			.select('*', { count: 'exact', head: true });

		if (existingCount && existingCount > 0) {
			return fail(400, {
				error: 'Setup has already been completed. Please sign in instead.'
			});
		}

		const formData = await request.formData();

		// Extract form fields
		const firstName = formData.get('first_name') as string;
		const lastName = formData.get('last_name') as string;
		const email = formData.get('email') as string;
		const password = formData.get('password') as string;
		const confirmPassword = formData.get('confirm_password') as string;

		// Validation
		const errors: Record<string, string> = {};

		if (!firstName || firstName.length < 2) {
			errors.first_name = 'First name must be at least 2 characters';
		}

		if (!lastName || lastName.length < 2) {
			errors.last_name = 'Last name must be at least 2 characters';
		}

		if (!email || !email.includes('@')) {
			errors.email = 'Please enter a valid email address';
		}

		if (!password || password.length < 8) {
			errors.password = 'Password must be at least 8 characters';
		}

		if (password !== confirmPassword) {
			errors.confirm_password = 'Passwords do not match';
		}

		// Return validation errors
		if (Object.keys(errors).length > 0) {
			return fail(400, {
				error: Object.values(errors)[0],
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Create user with admin service role (auto-confirms email)
		const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({
			email,
			password,
			email_confirm: true, // Auto-confirm email for initial admin
			user_metadata: {
				first_name: firstName,
				last_name: lastName
			}
		});

		if (authError) {
			console.error('Failed to create admin user:', authError);
			return fail(400, {
				error: authError.message,
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		if (!authData.user) {
			return fail(500, {
				error: 'Failed to create admin account. Please try again.',
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Get or create default membership status (active for admin)
		let statusId: string;
		const { data: activeStatus } = await supabaseAdmin
			.from('membership_statuses')
			.select('id')
			.eq('name', 'Active')
			.single();

		if (activeStatus) {
			statusId = activeStatus.id;
		} else {
			// Create active status if it doesn't exist
			const { data: newStatus, error: statusError } = await supabaseAdmin
				.from('membership_statuses')
				.insert({
					name: 'Active',
					description: 'Active member in good standing',
					is_default: false,
					color: '#22c55e'
				})
				.select('id')
				.single();

			if (statusError || !newStatus) {
				console.error('Failed to create membership status:', statusError);
				await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
				return fail(500, {
					error: 'Failed to set up membership status. Please try again.',
					first_name: firstName,
					last_name: lastName,
					email
				});
			}
			statusId = newStatus.id;
		}

		// Get or create default membership type
		let typeId: string;
		const { data: defaultType } = await supabaseAdmin
			.from('membership_types')
			.select('id')
			.eq('is_default', true)
			.single();

		if (defaultType) {
			typeId = defaultType.id;
		} else {
			// Create default membership type if it doesn't exist
			const { data: newType, error: typeError } = await supabaseAdmin
				.from('membership_types')
				.insert({
					name: 'Standard',
					description: 'Standard membership',
					annual_dues: 0,
					is_default: true
				})
				.select('id')
				.single();

			if (typeError || !newType) {
				console.error('Failed to create membership type:', typeError);
				await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
				return fail(500, {
					error: 'Failed to set up membership type. Please try again.',
					first_name: firstName,
					last_name: lastName,
					email
				});
			}
			typeId = newType.id;
		}

		// Create admin member profile
		const { error: memberError } = await supabaseAdmin.from('members').insert({
			id: authData.user.id,
			first_name: firstName,
			last_name: lastName,
			email,
			role: 'admin', // Set as admin
			membership_status_id: statusId,
			membership_type_id: typeId,
			nationality: ['US'] // Default nationality
		});

		if (memberError) {
			console.error('Failed to create admin member profile:', memberError);
			await supabaseAdmin.auth.admin.deleteUser(authData.user.id);
			return fail(500, {
				error: 'Failed to create admin profile. Please try again.',
				first_name: firstName,
				last_name: lastName,
				email
			});
		}

		// Success - redirect to login
		throw redirect(303, '/login?setup=complete');
	}
};
