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

function fromRow(row: Record<string, unknown>): GatewayConfig {
  return {
    id: row.id as string,
    processId: row.process_id as string,
    bpmnElementId: row.bpmn_element_id as string,
    gatewayType: row.gateway_type as GatewayConfig['gatewayType'],
    branches: Array.isArray(row.branches) ? row.branches as GatewayConfig['branches'] : [],
  }
}

export const supabaseGatewayRepo = {
  async save(gateway: GatewayConfig): Promise<void> {
    const { error } = await supabase.from('gateways').upsert({
      id: gateway.id,
      process_id: gateway.processId,
      bpmn_element_id: gateway.bpmnElementId,
      gateway_type: gateway.gatewayType,
      branches: gateway.branches,
      updated_at: new Date().toISOString(),
    })
    if (error) throw error
  },

  async saveMany(gateways: GatewayConfig[]): Promise<void> {
    if (gateways.length === 0) return
    const { error } = await supabase.from('gateways').upsert(
      gateways.map((g) => ({
        id: g.id,
        process_id: g.processId,
        bpmn_element_id: g.bpmnElementId,
        gateway_type: g.gatewayType,
        branches: g.branches,
        updated_at: new Date().toISOString(),
      }))
    )
    if (error) throw error
  },

  async getByProcess(processId: string): Promise<GatewayConfig[]> {
    const { data, error } = await supabase
      .from('gateways')
      .select('*')
      .eq('process_id', processId)
    if (error) throw error
    return (data ?? []).map(fromRow)
  },

  async deleteByProcess(processId: string): Promise<void> {
    const { error } = await supabase.from('gateways').delete().eq('process_id', processId)
    if (error) throw error
  },
}
