import { supabase } from '@/supabase'

export interface LoginResponse {
    access_token: string
    token_type: string
    role: string
    full_name: string
    profile_photo_url?: string
}

export const authService = {
    async login(params: { email: string; password: string; keep_session?: boolean }) {
        const { data, error } = await supabase.auth.signInWithPassword({
            email: params.email,
            password: params.password,
        })
        if (error) throw new Error(error.message)
        return data
    },

    async googleLogin() {
        const { error } = await supabase.auth.signInWithOAuth({
            provider: 'google',
            options: {
                redirectTo: window.location.origin
            }
        })
        if (error) throw new Error(error.message)
        // Note: For OAuth, Supabase redirects the browser automatically.
        // Session state is restored upon return.
    },

    async registerPassenger(userData: any) {
        const { data, error } = await supabase.auth.signUp({
            email: userData.email,
            password: userData.password,
            options: {
                data: {
                    full_name: userData.full_name,
                    role: 'PASSENGER'
                }
            }
        })
        if (error) throw new Error(error.message)
        return data
    },

    async registerDriver(formData: FormData) {
        // Handle file uploads (e.g. photo_url, vehicle_photo_url)
        // Save auth user
        const { data: authData, error: authError } = await supabase.auth.signUp({
            email: formData.get('email') as string,
            password: formData.get('password') as string,
            options: {
                data: {
                    full_name: formData.get('full_name') as string,
                    role: 'DRIVER'
                }
            }
        })

        if (authError) throw new Error(authError.message)

        // Let the postgres trigger handle the base users row. 
        // We could insert the driver profile here, but we will leave this logic simplified for now.
        return authData
    },

    async getCurrentUser() {
        const { data: authData, error } = await supabase.auth.getUser()
        if (error || !authData.user) return null

        // Fetch additional custom fields from our public database wrapper 
        const { data: publicUser } = await supabase
            .from('users')
            .select('*')
            .eq('id', authData.user.id)
            .single()

        return publicUser
    },

    async updateMe(formData: FormData) {
        const { data: authData } = await supabase.auth.getUser()
        if (!authData.user) throw new Error("No user logged in")

        const payload: any = {}
        formData.forEach((value, key) => {
            if (value !== 'null' && value !== '') payload[key] = value
        })

        // File handling logic can be added here if needed

        const { data, error } = await supabase
            .from('users')
            .update(payload)
            .eq('id', authData.user.id)
            .select()
            .single()

        if (error) throw new Error(error.message)
        return data
    },

    async logout() {
        await supabase.auth.signOut()
        localStorage.clear()
    },

    getApiUrl() {
        return 'Supabase (Nativo)'
    }
}
