import { supabase } from '@/lib/supabase'
import type { AppSettings } from '@/domain/types'

const DEFAULT_SETTINGS: AppSettings = { id: 'singleton', groupLabel: 'Cliente' }

// Elimina artículos iniciales que el usuario pudo haber ingresado por error (ej. "un Cliente" → "Cliente")
function normalizeGroupLabel(raw: string): string {
  return raw.replace(/^(un|una|el|la)\s+/i, '').trim() || 'Cliente'
}

export const supabaseSettingsRepo = {
  async get(): Promise<AppSettings> {
    const { data, error } = await supabase
      .from('app_settings')
      .select('id, group_label')
      .eq('id', 'singleton')
      .single()

    // PGRST116 = 0 rows — singleton aún no existe, crearlo y retornar el default
    if (error?.code === 'PGRST116' || !data) {
      await supabase.from('app_settings').upsert({
        id: 'singleton',
        group_label: 'Cliente',
      })
      return DEFAULT_SETTINGS
    }

    return { id: 'singleton', groupLabel: normalizeGroupLabel((data.group_label as string) ?? 'Cliente') }
  },

  async update(updates: Partial<Omit<AppSettings, 'id'>>): Promise<void> {
    const patch: Record<string, unknown> = { updated_at: new Date().toISOString() }
    if (updates.groupLabel !== undefined) patch.group_label = normalizeGroupLabel(updates.groupLabel)

    const { error } = await supabase
      .from('app_settings')
      .update(patch)
      .eq('id', 'singleton')
    if (error) throw error
  },
}
