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

async function getCurrentUserId(): Promise<string> {
  const { data: { session } } = await supabase.auth.getSession()
  if (!session?.user) throw new Error('Usuario no autenticado')
  return session.user.id
}

function fromRow(row: Record<string, unknown>): ProcessGroup {
  return {
    id: row.id as string,
    name: row.name as string,
    createdAt: new Date(row.created_at as string).getTime(),
    updatedAt: new Date(row.updated_at as string).getTime(),
  }
}

export const supabaseGroupRepo = {
  async save(group: ProcessGroup): Promise<void> {
    const userId = await getCurrentUserId()
    const { error } = await supabase.from('process_groups').upsert({
      id: group.id,
      name: group.name,
      created_by: userId,
      updated_at: new Date().toISOString(),
    })
    if (error) throw error
  },

  async getAll(): Promise<ProcessGroup[]> {
    const { data, error } = await supabase
      .from('process_groups')
      .select('*')
      .order('name', { ascending: true })
    if (error) throw error
    return (data ?? []).map(fromRow)
  },

  async getById(id: string): Promise<ProcessGroup | undefined> {
    const { data, error } = await supabase
      .from('process_groups')
      .select('*')
      .eq('id', id)
      .single()
    if (error) return undefined
    return fromRow(data)
  },

  async delete(id: string): Promise<void> {
    // La FK group_id en processes tiene ON DELETE SET NULL → procesos pasan a "Sin clasificar"
    const { error } = await supabase.from('process_groups').delete().eq('id', id)
    if (error) throw error
  },
}
