'use server'

import { createClient } from '@/lib/supabase/server'
import { getUserSession } from '@/lib/auth/permissions'
import { logger } from '@/lib/logger'

export interface MergeResult {
  success: boolean
  error?: string
}

export async function mergeRecords(
  entityType: string,
  tableName: string,
  existingId: string,
  existingRecord: Record<string, unknown>,
  incomingData: Record<string, unknown>,
  fieldResolutions: Record<string, 'keep_existing' | 'use_incoming'>
): Promise<MergeResult> {
  const session = await getUserSession()
  if (!session) return { success: false, error: 'Nicht angemeldet' }
  if (session.role !== 'admin' && session.role !== 'masteradmin') {
    return { success: false, error: 'Keine Berechtigung' }
  }

  // Build merged record starting from existing, then apply resolutions
  const mergedData: Record<string, unknown> = { ...existingRecord }

  // Remove internal keys from incoming before using its values
  const cleanedIncoming: Record<string, unknown> = { ...incomingData }
  delete cleanedIncoming['_status']
  delete cleanedIncoming['_error']

  for (const [field, resolution] of Object.entries(fieldResolutions)) {
    if (resolution === 'use_incoming') {
      mergedData[field] = cleanedIncoming[field]
    }
    // keep_existing: already set from existingRecord
  }

  // Remove id/timestamps from update payload
  const { id: _id, created_at: _ca, updated_at: _ua, ...updatePayload } = mergedData

  const supabase = await createClient()

  const { error: updateError } = await supabase
    .from(tableName)
    .update(updatePayload)
    .eq('id', existingId)

  if (updateError) {
    return { success: false, error: updateError.message }
  }

  const { error: auditError } = await supabase.from('master_data_audit_log').insert({
    action: 'merge',
    table_name: entityType,
    record_id: existingId,
    old_data: existingRecord,
    new_data: mergedData,
    details: {
      source_record: cleanedIncoming,
      field_resolutions: fieldResolutions,
    },
    changed_by: session.authUserId,
  })

  if (auditError) {
    logger.error('master_data.audit_log.insert_failed', auditError, { entity_type: entityType, table: tableName, record_id: existingId })
  }

  return { success: true }
}
