import { sql } from '@pgtyped/runtime'
import { EffectDbQueryAndValidateErrors, Redefine, effectDbQueryAndValidate } from '../../pg-database'
import { Pool } from 'pg'
import { z } from 'zod'
import { IInsertLogInternalQuery } from './logs.queries.types'
import { UtilisateurId } from 'camino-common/src/roles'
import { CaminoError } from 'camino-common/src/zod-tools'
import { Effect } from 'effect'
import { LogMethod } from 'camino-common/src/mutations'
import { CaminoRequest } from './express-type'

type Log = {
  utilisateur_id: UtilisateurId
  method: string
  path: string
  body: any
  camino_path: string
  camino_variables: Record<string, string>
}
export const addLog = (
  pool: Pool,
  utilisateur_id: UtilisateurId,
  method: LogMethod,
  req: Pick<CaminoRequest, 'url' | 'route' | 'body' | 'params'>
): Effect.Effect<void[], CaminoError<EffectDbQueryAndValidateErrors>> =>
  effectDbQueryAndValidate(insertLogInternal, { utilisateur_id, method, path: req.url, body: JSON.stringify(req.body), camino_path: req.route.path, camino_variables: req.params }, pool, z.void())

const insertLogInternal = sql<Redefine<IInsertLogInternalQuery, Log, void>>`
insert into logs (utilisateur_id, path, method, body, camino_path, camino_variables)
    values ($ utilisateur_id !, $path !, $ method !, $ body, $camino_path!, $camino_variables)
;
`
