import { sql } from '@pgtyped/runtime'
import { z } from 'zod'
import { effectDbQueryAndValidate, EffectDbQueryAndValidateErrors, Redefine } from '../../pg-database'
import { Effect } from 'effect'
import { DemarcheId } from 'camino-common/src/demarche'
import { CaminoError } from 'camino-common/src/zod-tools'
import { CaminoMachineId } from 'camino-common/src/validators/machine'
import { IUpdateMachineIdDbQuery } from './update-machine-id.queries.types'
import { Pool } from 'pg'

export type UpdateMachineIdErrors = EffectDbQueryAndValidateErrors
export const updateMachineId = (pool: Pool, demarcheId: DemarcheId, machineId: CaminoMachineId | null): Effect.Effect<DemarcheId, CaminoError<UpdateMachineIdErrors>> => {
  return effectDbQueryAndValidate(updateMachineIdDb, { demarcheId, machineId }, pool, z.void()).pipe(Effect.map(() => demarcheId))
}

const updateMachineIdDb = sql<Redefine<IUpdateMachineIdDbQuery, { machineId: CaminoMachineId | null; demarcheId: DemarcheId }, void>>`
UPDATE titres_demarches SET machine_id = $machineId! WHERE id = $demarcheId!
`
