'use server'

import { createAdminClient } from '@/lib/supabase/admin'
import { revalidatePath } from 'next/cache'

export type AdminSetupData = {
  email: string
  password: string
  companyName: string
  firstName: string
  lastName: string
}

export type SmtpSetupData = {
  host: string
  port: number
  secure: boolean
  user: string
  pass: string
}

/**
 * Checks if any user exists in the public.users table.
 * If count is 0, setup is required.
 */
export async function isSetupNeeded(): Promise<boolean> {
  try {
    const admin = createAdminClient()

    // 1. Check if any user exists in Supabase Auth
    const { data: authData, error: authError } = await admin.auth.admin.listUsers({
      perPage: 1
    })

    if (authError) {
      console.error('Error checking auth users list:', authError)
      return false
    }

    if (authData.users.length > 0) {
      return false
    }

    // 2. Check if any user exists in public.users table
    const { count, error: dbError } = await admin
      .from('users')
      .select('*', { count: 'exact', head: true })

    if (dbError) {
      console.error('Error checking users table status:', dbError)
      return false
    }

    return count === 0
  } catch (e) {
    console.error('Exception checking setup status:', e)
    return false
  }
}

/**
 * Completes the initial setup by creating the first admin user,
 * updating their role and profile, and storing SMTP settings.
 */
export async function completeSetup(
  adminData: AdminSetupData,
  smtpData: SmtpSetupData
): Promise<{ success: boolean; error?: string }> {
  try {
    // 1. Double check if setup is actually needed to prevent double runs
    const needed = await isSetupNeeded()
    if (!needed) {
      return { success: false, error: 'Setup bereits abgeschlossen.' }
    }

    const admin = createAdminClient()

    // 2. Create user in Supabase Auth
    const { data: authData, error: authError } = await admin.auth.admin.createUser({
      email: adminData.email,
      password: adminData.password,
      email_confirm: true,
    })

    if (authError || !authData.user) {
      return { success: false, error: `Fehler beim Erstellen des Admin-Kontos: ${authError?.message}` }
    }

    const userId = authData.user.id

    // 3. Update user role to admin in public.users
    const { error: roleError } = await admin
      .from('users')
      .update({ role: 'admin' })
      .eq('id', userId)

    if (roleError) {
      console.error('Error setting user role to admin:', roleError)
    }

    // 4. Update company and name details in public.profiles
    const { error: profileError } = await admin
      .from('profiles')
      .update({
        company_name: adminData.companyName,
        first_name: adminData.firstName,
        last_name: adminData.lastName,
        email: adminData.email,
      })
      .eq('id', userId)

    if (profileError) {
      console.error('Error updating admin profile:', profileError)
    }

    // 5. Store SMTP configuration in public.settings
    const { error: smtpError } = await admin
      .from('settings')
      .upsert({
        id: 'smtp',
        host: smtpData.host,
        port: smtpData.port,
        secure: smtpData.secure,
        user: smtpData.user,
        pass: smtpData.pass,
        updated_at: new Date().toISOString(),
      })

    if (smtpError) {
      console.error('Error saving SMTP settings:', smtpError)
      return { success: false, error: `Fehler beim Speichern der SMTP-Einstellungen: ${smtpError.message}` }
    }

    revalidatePath('/')
    return { success: true }
  } catch (e: any) {
    console.error('Exception during completeSetup:', e)
    return { success: false, error: e.message || 'Unerwarteter Fehler beim Setup.' }
  }
}
