import { redirect } from "@tanstack/react-router"
import { createServerFn } from "@tanstack/react-start"
import { getSupabaseServerClient } from "@/integrations/supabase/supabase"
import { loginFormSchema, signupFormSchema } from "../validation/user"

export const getUser = createServerFn().handler(async () => {
	const supabase = getSupabaseServerClient()
	const { data, error } = await supabase.auth.getUser()
	if (error || !data.user) {
		return {
			error: true,
			message: error?.message ?? "Unknown error"
		}
	}
	console.log(data)
	return {
		user: {
			id: data.user.id,
			email: data.user.email,
			name: data.user.user_metadata.name || "",
			location: data.user.user_metadata.location || ""
		},
		error: false
	}
})

export const loginUser = createServerFn({
	method: "POST"
})
	.inputValidator(loginFormSchema)
	.handler(async ({ data }) => {
		const supabase = getSupabaseServerClient()
		const login = await supabase.auth.signInWithPassword({
			email: data.email,
			password: data.password
		})
		if (login.error) {
			return {
				error: true,
				message: login.error.message
			}
		}

		return {
			error: false
		}
	})

export const logoutUser = createServerFn().handler(async () => {
	const supabase = getSupabaseServerClient()

	const { error } = await supabase.auth.signOut()
	if (error) {
		return {
			error: true,
			message: error.message
		}
	}

	throw redirect({
		to: "/",
		viewTransition: true,
		replace: true
	})
})

export const signupUser = createServerFn({ method: "POST" })
	.inputValidator(signupFormSchema)
	.handler(async ({ data }) => {
		const supabase = getSupabaseServerClient()
		const { error } = await supabase.auth.signUp({
			email: data.email,
			password: data.password,
			options: {
				// Estos son los metadatos
				data: {
					name: data.name,
					location: data.location
				}
			}
		})
		if (error) {
			return {
				error: true,
				message: error.message
			}
		}

		throw redirect({
			href: data.redirectUrl || "/"
		})
	})

// TODO: Add resend confirmation email function
