import { dbManager } from '../../../tests/db-manager'
import { afterAll, beforeAll, test, expect, vi, describe } from 'vitest'
import type { Pool } from 'pg'
import { newDemarcheId, newEtapeId, newTitreId } from '../../database/models/_format/id-create'
import { insertTitreGraph } from '../../../tests/integration-test-helper'
import { titreSlugValidator } from 'camino-common/src/validators/titres'
import { restDownloadCall } from '../../../tests/_utils'
import { ADMINISTRATION_IDS } from 'camino-common/src/static/administrations'
import { HTTP_STATUS } from 'camino-common/src/http'
import { ETAPE_IS_NOT_BROUILLON } from 'camino-common/src/etape'
import { ETAPES_STATUTS } from 'camino-common/src/static/etapesStatuts'
import { ETAPES_TYPES } from 'camino-common/src/static/etapesTypes'
import { toCaminoDate } from 'camino-common/src/date'
import { DEMARCHES_TYPES_IDS } from 'camino-common/src/static/demarchesTypes'
import { GEO_SYSTEME_IDS } from 'camino-common/src/static/geoSystemes'
import { FeatureMultiPolygon } from 'camino-common/src/perimetre'

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

let dbPool: Pool

const multiPolygonWith4Points: FeatureMultiPolygon = {
  type: 'Feature',
  properties: {},
  geometry: {
    type: 'MultiPolygon',
    coordinates: [
      [
        [
          [-53.16822754488772, 5.02935254143807],
          [-53.15913163720232, 5.029382753429523],
          [-53.15910186841349, 5.020342601941031],
          [-53.168197650929095, 5.02031244452273],
          [-53.16822754488772, 5.02935254143807],
        ],
      ],
    ],
  },
}

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

  const titreId = newTitreId('titre-id-1-for-import')
  const titreSlug = titreSlugValidator.parse('titre-slug-1-for-import')
  const demarcheId = newDemarcheId('demarche-id-1-for-import')
  const etapeId = newEtapeId('etape-id-1-for-import')
  await insertTitreGraph({
    id: titreId,
    slug: titreSlug,
    nom: 'nomTitre',
    typeId: 'arm',
    titreStatutId: 'val',
    propsTitreEtapesIds: { points: etapeId },
    demarches: [
      {
        id: demarcheId,
        titreId: titreId,
        typeId: DEMARCHES_TYPES_IDS.Octroi,
        etapes: [
          {
            id: etapeId,
            titreDemarcheId: demarcheId,
            date: toCaminoDate('2025-01-01'),
            typeId: ETAPES_TYPES.demande,
            statutId: ETAPES_STATUTS.FAIT,
            isBrouillon: ETAPE_IS_NOT_BROUILLON,
            geojsonOrigineGeoSystemeId: GEO_SYSTEME_IDS.WGS84,
            geojson4326Perimetre: multiPolygonWith4Points,
            geojsonOriginePerimetre: multiPolygonWith4Points,
          },
        ],
      },
    ],
  })
})

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

describe('titres', async () => {
  test('peut télécharger les titres en csv', async () => {
    const tested = await restDownloadCall(
      dbPool,
      '/titres',
      {},
      {
        role: 'admin',
        administrationId: ADMINISTRATION_IDS['DGTM - GUYANE'],
      },
      { format: 'csv' }
    )

    expect(tested.text).toMatchInlineSnapshot(`
      "id,nom,type,domaine,date_debut,date_fin,date_demande,statut,substances,surface renseignee km2,communes (surface calculee km2),forets,facades_maritimes,departements,regions,administrations_noms,titulaires_noms,titulaires_adresses,titulaires_legal,titulaires_categorie,amodiataires_noms,amodiataires_adresses,amodiataires_legal,amodiataires_categorie,geojson,Franchissements de cours d'eau,Prospection mécanisée
      titre-slug-1-for-import,nomTitre,autorisation de recherches,minéraux et métaux,,,,valide,,,,,,,,Direction Générale des Territoires et de la Mer de Guyane,,,,,,,,,"{""type"":""MultiPolygon"",""coordinates"":[[[[-53.16822754488772,5.02935254143807],[-53.15913163720232,5.029382753429523],[-53.15910186841349,5.020342601941031],[-53.168197650929095,5.02031244452273],[-53.16822754488772,5.02935254143807]]]]}",0,Non"
    `)
  })
  test('peut télécharger les titres en xlsx', async () => {
    const tested = await restDownloadCall(
      dbPool,
      '/titres',
      {},
      {
        role: 'admin',
        administrationId: ADMINISTRATION_IDS['DGTM - GUYANE'],
      },
      { format: 'xlsx' }
    )

    expect(tested.statusCode).toStrictEqual(HTTP_STATUS.OK)
  })

  test('peut télécharger les titres en ods', async () => {
    const tested = await restDownloadCall(
      dbPool,
      '/titres',
      {},
      {
        role: 'admin',
        administrationId: ADMINISTRATION_IDS['DGTM - GUYANE'],
      },
      { format: 'ods' }
    )

    expect(tested.statusCode).toStrictEqual(HTTP_STATUS.OK)
  })

  test('peut télécharger les titres en geojson', async () => {
    const tested = await restDownloadCall(
      dbPool,
      '/titres',
      {},
      {
        role: 'admin',
        administrationId: ADMINISTRATION_IDS['DGTM - GUYANE'],
      },
      { format: 'geojson' }
    )

    expect(tested.body).toMatchInlineSnapshot(`
      {
        "features": [
          {
            "geometry": {
              "coordinates": [
                [
                  [
                    [
                      -53.16822754488772,
                      5.02935254143807,
                    ],
                    [
                      -53.15913163720232,
                      5.029382753429523,
                    ],
                    [
                      -53.15910186841349,
                      5.020342601941031,
                    ],
                    [
                      -53.168197650929095,
                      5.02031244452273,
                    ],
                    [
                      -53.16822754488772,
                      5.02935254143807,
                    ],
                  ],
                ],
              ],
              "type": "MultiPolygon",
            },
            "properties": {
              "administrations_noms": [
                "Direction Générale des Territoires et de la Mer de Guyane",
              ],
              "amodiataires_legal": [],
              "amodiataires_noms": [],
              "communes": [],
              "date_debut": null,
              "date_demande": null,
              "date_fin": null,
              "departements": [],
              "domaine": "minéraux et métaux",
              "facades_maritimes": [],
              "forets": [],
              "franchissements_de_cours_d_eau": "0",
              "id": "titre-slug-1-for-import",
              "nom": "nomTitre",
              "prospection_mecanisee": "Non",
              "references": [],
              "regions": [],
              "statut": "valide",
              "substances": [],
              "surface_par_communes": [],
              "surface_totale": null,
              "titulaires_legal": [],
              "titulaires_noms": [],
              "type": "autorisation de recherches",
            },
            "type": "Feature",
          },
        ],
        "type": "FeatureCollection",
      }
    `)
  })
})
