import { fail, redirect } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { auth } from '$lib/server/auth';
import { db } from '$lib/server/db';
import { session } from '$lib/server/db/auth.schema';
import { eq } from 'drizzle-orm';
import { APIError } from 'better-auth/api';

export const load: PageServerLoad = async (event) => {
	if (!event.locals.user) {
		return redirect(302, '/login');
	}

	// Fetch all sessions for this user
	const userSessions = await db
		.select()
		.from(session)
		.where(eq(session.userId, event.locals.user.id));

	return {
		user: event.locals.user,
		sessions: userSessions
	};
};

export const actions: Actions = {
	updateProfile: async (event) => {
		if (!event.locals.user) {
			return redirect(302, '/login');
		}

		const formData = await event.request.formData();
		const name = formData.get('name')?.toString() ?? '';

		if (!name.trim()) {
			return fail(400, { message: 'Le nom ne peut pas être vide' });
		}

		try {
			await auth.api.updateUser({
				body: {
					name: name.trim()
				},
				headers: event.request.headers
			});
		} catch (error) {
			if (error instanceof APIError) {
				return fail(400, { message: error.message || 'Erreur lors de la mise à jour' });
			}
			return fail(500, { message: 'Erreur inattendue' });
		}

		return { success: true };
	},
	changePassword: async (event) => {
		if (!event.locals.user) {
			return redirect(302, '/login');
		}

		const formData = await event.request.formData();
		const oldPassword = formData.get('oldPassword')?.toString() ?? '';
		const newPassword = formData.get('newPassword')?.toString() ?? '';
		const confirmPassword = formData.get('confirmPassword')?.toString() ?? '';

		if (!oldPassword.trim()) {
			return fail(400, { message: 'Le mot de passe actuel est requis' });
		}

		if (!newPassword.trim()) {
			return fail(400, { message: 'Le nouveau mot de passe est requis' });
		}

		if (newPassword !== confirmPassword) {
			return fail(400, { message: 'Les mots de passe ne correspondent pas' });
		}

		if (newPassword.length < 8) {
			return fail(400, { message: 'Le mot de passe doit contenir au moins 8 caractères' });
		}

		try {
			await auth.api.changePassword({
				body: {
					currentPassword: oldPassword,
					newPassword
				},
				headers: event.request.headers
			});
		} catch (error) {
			if (error instanceof APIError) {
				return fail(400, { message: error.message || 'Erreur lors du changement de mot de passe' });
			}
			return fail(500, { message: 'Erreur inattendue' });
		}

		return { success: true };
	},
	revokeSession: async (event) => {
		if (!event.locals.user) {
			return redirect(302, '/login');
		}

		const formData = await event.request.formData();
		const sessionId = formData.get('sessionId')?.toString() ?? '';

		if (!sessionId) {
			return fail(400, { message: 'ID de session manquant' });
		}

		try {
			// Delete the session from database
			await db.delete(session).where(eq(session.id, sessionId));
		} catch (error) {
			return fail(500, { message: 'Erreur lors de la révocation de la session' });
		}

		return { success: true, message: 'Session révoquée avec succès' };
	}
};
