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

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

export const supabaseSettingsRepo = {
  async get(): Promise<AppSettings> {
    const { data } = await supabase
      .from('app_settings')
      .select('id, group_label')
      .eq('id', 'singleton')
      .single()
    if (!data) return DEFAULT_SETTINGS
    return { id: 'singleton', groupLabel: (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 = updates.groupLabel

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