'use server'

import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
import { createClient } from '@/utils/supabase/server'

export async function signup(formData: FormData) {
  const supabase = await createClient()

  // type-casting here for convenience
  // in practice, you should validate your inputs
  const name = formData.get('name') as string
  const email = formData.get('email') as string
  const password = formData.get('password') as string

  const { data, error } = await supabase.auth.signUp({
    email,
    password,
    options: {
      data: {
        full_name: name,
      }
    }
  })

  if (error) {
    redirect('/signup?error=Could not authenticate user')
  }

  // After signup, we might want to automatically create a profile record or let a trigger handle it.
  // Wait, the trigger "handle_new_user" should handle the creation of the record in the 'usuarios' table if implemented in Supabase.
  
  if (data.session) {
      redirect('/onboarding')
  } else {
      // requires email verification
      redirect('/login?message=Check your email to continue sign in process')
  }
}
