import { apiGraphQLFetch } from '@/api/_client'
import { newGetWithJson } from '@/api/client-rest'
import { Journaux, JournauxQueryParams } from 'camino-common/src/journaux'
import { GetMutation, Mutation, MutationId } from 'camino-common/src/mutations'
import { CaminoError } from 'camino-common/src/zod-tools'
import gql from 'graphql-tag'

export interface JournauxApiClient {
  getJournaux: (params: JournauxQueryParams) => Promise<Journaux>
  getMutations: (email: string | undefined) => Promise<Mutation[] | CaminoError<string>>
  getMutation: (mutationId: MutationId) => Promise<GetMutation | CaminoError<string>>
}

export const journauxApiClient: JournauxApiClient = {
  getMutations: email => newGetWithJson('/rest/mutations', {}, { emails: email }),
  getMutation: mutationId => newGetWithJson('/rest/mutations/:mutationId', { mutationId }),
  // TODO 2023-06-22 check with zod?
  getJournaux: async (params: JournauxQueryParams): Promise<Journaux> =>
    apiGraphQLFetch(gql`
      query Journaux($page: Int!, $recherche: String, $titresIds: [String]) {
        journaux(page: $page, recherche: $recherche, titresIds: $titresIds) {
          elements {
            id
            date
            differences
            elementId
            operation
            utilisateur {
              nom
              prenom
            }
            titre {
              nom
            }
          }
          total
        }
      }
    `)({
      ...params,
    }),
}
