import axios, { AxiosRequestConfig } from 'axios'
import { DateTime } from 'luxon'
import { toast } from 'react-toastify'
import {
  GrdfConsentEntity,
  GrdfConsentPaginationEntity,
  IGrdfConsent,
  IGrdfConsentPagination,
} from '../models/grdfConsent'

export class GrdfConsentService {
  /**
   * Search for consents
   * @param search
   * @param limit
   * @param page
   * @param axiosHeaders
   */
  public searchConsents = async (
    search: string,
    limit: number,
    page: number,
    axiosHeaders: AxiosRequestConfig
  ): Promise<IGrdfConsentPagination | null> => {
    try {
      const { data } = await axios.get<GrdfConsentPaginationEntity>(
        `/api/admin/grdf/consent?search=${search}&limit=${limit}&page=${page}`,
        axiosHeaders
      )
      return this.parseConsentPagination(data)
    } catch (e) {
      if (e.response.status === 403) {
        toast.error("Accès refusé : vous n'avez pas les droits nécessaires")
      } else {
        toast.error('Erreur lors de la récupération des consentements')
      }
      console.error(e)
      return null
    }
  }

  /**
   * Converts consent entity into consent
   * @param consentEntity
   */
  public parseConsent = (consentEntity: GrdfConsentEntity): IGrdfConsent => {
    const startDate = DateTime.fromISO(consentEntity.CreatedAt, {
      zone: 'utc',
    }).setLocale('fr-FR')
    const endDate = DateTime.fromISO(consentEntity.endDate, {
      zone: 'utc',
    }).setLocale('fr-FR')

    return {
      ID: consentEntity.ID,
      startDate: startDate,
      endDate: endDate,
      firstname: consentEntity.firstname,
      lastname: consentEntity.lastname,
      pce: consentEntity.pce,
      postalCode: consentEntity.postalCode,
    }
  }

  /**
   * Converts consent pagination entity into consent pagination
   * @param consentPaginationEntity
   */
  public parseConsentPagination = (
    consentPaginationEntity: GrdfConsentPaginationEntity
  ): IGrdfConsentPagination => {
    const rows = consentPaginationEntity.rows.map(consent =>
      this.parseConsent(consent)
    )

    const consentPagination: IGrdfConsentPagination = {
      rows: rows,
      totalRows: consentPaginationEntity.totalRows,
      totalPages: consentPaginationEntity.totalPages,
    }
    return consentPagination
  }
}