import { supabase } from '@/lib/supabase'
import type { Simulation, SimulationResult } from '@/domain/types'

function fromRow(row: Record<string, unknown>): Simulation {
  return {
    id: row.id as string,
    processId: row.process_id as string,
    executedAt: Number(row.executed_at),
    result: row.result as SimulationResult,
    resultAutomated: row.result_automated != null
      ? (row.result_automated as SimulationResult)
      : undefined,
  }
}

export const supabaseSimulationRepo = {
  async save(simulation: Simulation): Promise<void> {
    const { error } = await supabase.from('simulations').insert({
      id: simulation.id,
      process_id: simulation.processId,
      executed_at: simulation.executedAt,
      result: simulation.result,
      result_automated: simulation.resultAutomated ?? null,
    })
    if (error) throw error
  },

  async getLatestByProcess(processId: string): Promise<Simulation | undefined> {
    const { data, error } = await supabase
      .from('simulations')
      .select('*')
      .eq('process_id', processId)
      .order('executed_at', { ascending: false })
      .limit(1)
      .maybeSingle()
    if (error || !data) return undefined
    return fromRow(data as Record<string, unknown>)
  },

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