'use server'
import { createAdminClient } from '@/lib/supabase/admin'
import { revalidatePath, unstable_noStore as noStore } from 'next/cache'

export async function getCompanies() {
  noStore()
  const admin = createAdminClient()
  const { data, error } = await admin.from('companies').select('*')
  if (error) throw error
  return data
}

export async function createCompany(data: { name: string; street?: string; zip?: string; city?: string; email?: string }) {
  const admin = createAdminClient()
  const { data: dbData, error } = await admin.from('companies').insert({
    name: data.name,
    street: data.street || null,
    zip: data.zip || null,
    city: data.city || null,
    email: data.email || null,
  }).select().single()
  if (error) throw error
  revalidatePath('/admin/companies')
  revalidatePath('/admin/users')
  return dbData
}

export async function updateCompany(id: string, data: { name: string; street?: string; zip?: string; city?: string; email?: string }) {
  const admin = createAdminClient()
  const { data: dbData, error } = await admin.from('companies').update({
    name: data.name,
    street: data.street || null,
    zip: data.zip || null,
    city: data.city || null,
    email: data.email || null,
  }).eq('id', id).select().single()
  if (error) throw error
  revalidatePath('/admin/companies')
  revalidatePath('/admin/users')
  return dbData
}

export async function deleteCompany(id: string) {
  const admin = createAdminClient()
  const { error } = await admin.from('companies').delete().eq('id', id)
  if (error) throw error
  revalidatePath('/admin/companies')
  revalidatePath('/admin/users')
  return true
}

export async function assignCompanyToUser(userId: string, companyId: string | null) {
  const admin = createAdminClient()
  const { error } = await admin.from('users').update({ company_id: companyId }).eq('id', userId)
  if (error) throw error
  revalidatePath('/admin/users')
  return true
}

export async function getEndCustomersByCompany(companyId: string) {
  const admin = createAdminClient()
  
  // 1. Get all partners of this company
  const { data: partners, error: partnersError } = await admin
    .from('users')
    .select('id')
    .eq('company_id', companyId)
  if (partnersError) throw partnersError

  if (!partners || partners.length === 0) return []

  const partnerIds = partners.map((p) => p.id)

  // 2. Get all end customers belonging to these partners
  const { data: customers, error: customersError } = await admin
    .from('end_customers')
    .select('*')
    .in('partner_id', partnerIds)
  if (customersError) throw customersError

  return customers || []
}

export async function getCompanyDetails(companyId: string) {
  const admin = createAdminClient()
  const { data, error } = await admin.from('companies').select('*').eq('id', companyId).single()
  if (error) throw error
  return data
}

export async function getEndCustomersByCompanyWithPartners(companyId: string) {
  const admin = createAdminClient()
  
  // 1. Get all partners of this company
  const { data: partners, error: partnersError } = await admin
    .from('users')
    .select('id')
    .eq('company_id', companyId)
  if (partnersError) throw partnersError

  if (!partners || partners.length === 0) return []

  const partnerIds = partners.map((p) => p.id)

  // 2. Get all end customers belonging to these partners
  const { data: customers, error: customersError } = await admin
    .from('end_customers')
    .select('*')
    .in('partner_id', partnerIds)
  if (customersError) throw customersError

  // 3. Get profiles of all these partners to resolve their names
  const { data: profiles, error: profilesError } = await admin
    .from('profiles')
    .select('id, first_name, last_name')
    .in('id', partnerIds)
  if (profilesError) throw profilesError

  // Get user emails
  const { data: { users }, error: authError } = await admin.auth.admin.listUsers()
  const emailMap = new Map((users || []).map(u => [u.id, u.email || '']))

  const profileMap = new Map((profiles || []).map((p) => [p.id, p]))

  return customers.map((c) => {
    const prof = profileMap.get(c.partner_id)
    return {
      ...c,
      partner_name: prof ? `${prof.first_name || ''} ${prof.last_name || ''}`.trim() || emailMap.get(c.partner_id) || 'Unbekannt' : emailMap.get(c.partner_id) || 'Unbekannt',
    }
  })
}

export async function getCompanyPartners(companyId: string) {
  const admin = createAdminClient()
  const { data: usersData, error: usersError } = await admin
    .from('users')
    .select('id, role')
    .eq('company_id', companyId)
  if (usersError) throw usersError

  if (!usersData || usersData.length === 0) return []

  const userIds = usersData.map(u => u.id)

  const { data: profiles, error: profilesError } = await admin
    .from('profiles')
    .select('id, first_name, last_name')
    .in('id', userIds)
  if (profilesError) throw profilesError

  const { data: { users }, error: authError } = await admin.auth.admin.listUsers()
  const emailMap = new Map((users || []).map(u => [u.id, u.email || '']))

  const profileMap = new Map((profiles || []).map(p => [p.id, p]))

  return usersData.map(u => {
    const prof = profileMap.get(u.id)
    return {
      id: u.id,
      email: emailMap.get(u.id) || '',
      name: prof ? `${prof.first_name || ''} ${prof.last_name || ''}`.trim() || emailMap.get(u.id) || 'Unbekannt' : emailMap.get(u.id) || 'Unbekannt',
    }
  })
}

export async function adminCreateEndCustomer(data: {
  partner_id: string
  company_name: string
  vat_id?: string
  first_name?: string
  last_name?: string
  street?: string
  zip?: string
  city?: string
  email?: string
}) {
  const admin = createAdminClient()
  const { data: dbData, error } = await admin
    .from('end_customers')
    .insert([{
      partner_id: data.partner_id,
      company_name: data.company_name,
      vat_id: data.vat_id || null,
      first_name: data.first_name || null,
      last_name: data.last_name || null,
      street: data.street || null,
      zip: data.zip || null,
      city: data.city || null,
      email: data.email || null,
    }])
    .select()
    .single()
  if (error) throw error
  return dbData
}

export async function adminUpdateEndCustomer(id: string, data: {
  partner_id: string
  company_name: string
  vat_id?: string
  first_name?: string
  last_name?: string
  street?: string
  zip?: string
  city?: string
  email?: string
}) {
  const admin = createAdminClient()
  const { data: dbData, error } = await admin
    .from('end_customers')
    .update({
      partner_id: data.partner_id,
      company_name: data.company_name,
      vat_id: data.vat_id || null,
      first_name: data.first_name || null,
      last_name: data.last_name || null,
      street: data.street || null,
      zip: data.zip || null,
      city: data.city || null,
      email: data.email || null,
    })
    .eq('id', id)
    .select()
    .single()
  if (error) throw error
  return dbData
}

export async function adminDeleteEndCustomer(id: string) {
  const admin = createAdminClient()
  const { error } = await admin
    .from('end_customers')
    .delete()
    .eq('id', id)
  if (error) throw error
  return true
}

