'use server'

import { createClient } from '@/lib/supabase/server'
import { verifyAdmin } from '@/lib/actions/auth'

export async function getDatabaseIntegrity() {
  try {
    await verifyAdmin()
    const supabase = await createClient()
    const { data, error } = await supabase.rpc('check_database_integrity')
    if (error) {
      return { success: false, error: error.message }
    }
    return { success: true, data }
  } catch (err: any) {
    console.error("Error in getDatabaseIntegrity:", err)
    return { success: false, error: err.message || "Unerwarteter Fehler beim Integritätsscan." }
  }
}

export async function repairDatabaseSchema() {
  try {
    await verifyAdmin()
    const supabase = await createClient()
    const { data, error } = await supabase.rpc('repair_database_schema')
    if (error) {
      return { success: false, error: error.message }
    }
    return { success: true, data }
  } catch (err: any) {
    console.error("Error in repairDatabaseSchema:", err)
    return { success: false, error: err.message || "Unerwarteter Fehler bei der Schemareparatur." }
  }
}

export async function optimizeDatabaseIndices() {
  try {
    await verifyAdmin()
    const supabase = await createClient()
    const { data, error } = await supabase.rpc('optimize_database_indices')
    if (error) {
      return { success: false, error: error.message }
    }
    return { success: true, data }
  } catch (err: any) {
    console.error("Error in optimizeDatabaseIndices:", err)
    return { success: false, error: err.message || "Unerwarteter Fehler bei der Indexoptimierung." }
  }
}
