import { dbManager } from '../../../tests/db-manager'
import { restNewCall } from '../../../tests/_utils/index'
import { afterAll, beforeAll, describe, test, expect, vi, beforeEach } from 'vitest'
import type { Pool } from 'pg'
import { ADMINISTRATION_IDS } from 'camino-common/src/static/administrations'
import { mutationIdValidator } from 'camino-common/src/mutations'
import { createUtilisateur } from '../../database/queries/utilisateurs.queries'
import { getCurrent } from 'camino-common/src/date'
import { newUtilisateurId } from '../../database/models/_format/id-create'
import { callAndExit } from '../../tools/fp-tools'
import { addLog } from './logs.queries'
import { HTTP_STATUS } from 'camino-common/src/http'

console.info = vi.fn()
console.warn = vi.fn()
console.error = vi.fn()

beforeEach(() => {
  vi.resetAllMocks()
})

let dbPool: Pool

beforeAll(async () => {
  const { pool } = await dbManager.populateDb()
  dbPool = pool

  const userId = newUtilisateurId('userIdForMutation')
  await createUtilisateur(dbPool, {
    role: 'defaut',
    id: userId,
    email: '',
    nom: '',
    prenom: '',
    telephone_fixe: null,
    telephone_mobile: null,
    date_creation: getCurrent(),
    keycloak_id: '',
  })
  await callAndExit(
    addLog(dbPool, userId, 'post', {
      params: {},
      url: '/rest/anyurl',
      body: {},
      route: { path: 'path' },
    })
  )
})

afterAll(async () => {
  await dbManager.closeKnex()
})

describe('getMutations', () => {
  test('ne peut pas récupérer les mutations si non super', async () => {
    const tested = await restNewCall(dbPool, '/rest/mutations', {}, { role: 'admin', administrationId: ADMINISTRATION_IDS['DGALN/DEB/EARM2'] })

    expect(tested.body).toMatchInlineSnapshot(`
      {
        "message": "Droits insuffisants",
        "status": 403,
      }
    `)
  })
  test('récupère les mutations, puis une seule', async () => {
    let tested = await restNewCall(dbPool, '/rest/mutations', {}, { role: 'super' })

    expect(tested.body, JSON.stringify(tested.body)).toHaveLength(1)
    const mutationId = tested.body[0].id
    tested = await restNewCall(dbPool, '/rest/mutations/:mutationId', { mutationId: mutationId }, { role: 'super' })
    expect(tested.statusCode, JSON.stringify(tested.body)).toBe(HTTP_STATUS.OK)
  })
})

describe('getMutation', () => {
  test('ne peut pas récupérer une mutation si non super', async () => {
    const mutationId = mutationIdValidator.parse('3b1d61bc-1f62-445c-a18f-22ca95b82fc3')
    const tested = await restNewCall(dbPool, '/rest/mutations/:mutationId', { mutationId: mutationId }, { role: 'admin', administrationId: ADMINISTRATION_IDS['DGALN/DEB/EARM2'] })

    expect(tested.body).toMatchInlineSnapshot(`
      {
        "message": "Droits insuffisants",
        "status": 403,
      }
    `)
  })
})
