import { redirect } from "@tanstack/react-router"
import { createServerFn } from "@tanstack/react-start"
import { eq } from "drizzle-orm"
import { db } from "@/integrations/drizzle"
import { profiles, users } from "@/integrations/drizzle/db/schema"
import { getSupabaseServerClient } from "@/integrations/supabase/supabase"
import {
	loginFormSchema,
	profileFormSchema,
	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"
})
	.validator(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" })
	.validator(signupFormSchema)
	.handler(async ({ data }) => {
		const supabase = getSupabaseServerClient()
		const { error } = await supabase.auth.signUp({
			email: data.email,
			password: data.password,
			options: {
				data: {
					name: data.name,
					location: data.location
				}
			}
		})
		if (error) {
			return {
				error: true,
				message: error.message
			}
		}

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

export const getAllUsers = createServerFn().handler(async () => {
	const response = await db.select().from(users)
	return response
})

export const createProfile = createServerFn({ method: "POST" })
	.validator(profileFormSchema)
	.handler(async ({ data }) => {
		await db.insert(profiles).values(data).returning()
	})

export const getProfile = createServerFn({ method: "POST" })
	.validator((data: { id: string }) => data)
	.handler(async ({ data }) => {
		const { id } = data
		const response = await db
			.select()
			.from(profiles)
			.where(eq(profiles.id, id))
			.limit(1)

		return response[0] ?? null
	})
