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

function fromRow(row: Record<string, unknown>): Area {
  return {
    id: row.id as string,
    orgId: row.org_id as string,
    name: row.name as string,
    description: (row.description as string | null) ?? null,
    createdAt: new Date(row.created_at as string).getTime(),
  }
}

export const supabaseAreaRepo = {
  async getByOrg(orgId: string): Promise<Area[]> {
    const { data, error } = await supabase
      .from('areas')
      .select('*')
      .eq('org_id', orgId)
      .order('name', { ascending: true })
    if (error) throw error
    return (data ?? []).map(fromRow)
  },

  async create(data: { orgId: string; name: string; description?: string }): Promise<Area> {
    const { data: row, error } = await supabase
      .from('areas')
      .insert({
        org_id: data.orgId,
        name: data.name,
        description: data.description ?? null,
      })
      .select('*')
      .single()
    if (error) throw error
    return fromRow(row as Record<string, unknown>)
  },

  async update(id: string, data: { name?: string; description?: string }): Promise<Area> {
    const { data: row, error } = await supabase
      .from('areas')
      .update({
        ...(data.name !== undefined && { name: data.name }),
        ...(data.description !== undefined && { description: data.description }),
        updated_at: new Date().toISOString(),
      })
      .eq('id', id)
      .select('*')
      .single()
    if (error) throw error
    return fromRow(row as Record<string, unknown>)
  },

  // Los procesos con esta área pasan a area_id = null (ON DELETE SET NULL en migración 017)
  async delete(id: string): Promise<void> {
    const { error } = await supabase.from('areas').delete().eq('id', id)
    if (error) throw error
  },
}
