/* eslint-disable import/no-unresolved */
import { loginInterface, loginResponseInterface, resetPassInterface, UserInterface } from '@/types/userInterface';
import { API_ENDPOINTS } from '@/config/apiConfig';
import { pdfInterface, responseDefault, SageDocumentType, SignatureRequest, StatusRequest, StatusResponse, TransformationResponse, TypeDocument, UniversignType } from '@/types/sageTypes';
import { Client, ClientCreateResponse, ClientRequest, ClientUpdateRequest, ContactRequest, Contacts } from '@/types/clientType';
import apiService, { BackUrl } from './api';
import { Article, ArticleRequest, ArticleUpdateRequest, StockRequest, StockResponse } from '@/types/articleType';
import { DevisDetail, DevisListItem, DevisRequest, DevisResponse, DevisUpdateRequest } from '@/types/devisType';
import { Commande, CommandeRequest, CommandeResponse, CommandeUpdateRequest } from '@/types/commandeTypes';
import { Facture, FactureRequest, FactureUpdateRequest, FactureValideResponse, RelanceRequest, RelanceResponse } from '@/types/factureType';
import { BL, BLRequest, BLUpdateRequest } from '@/types/BL_Types';
import { Fournisseur, FournisseurRequest, FournisseurUpdateRequest } from '@/types/fournisseurType';
import { Avoir, AvoirRequest, AvoirUpdateRequest } from '@/types/avoirType';
import { Famille, FamilleRequest } from '@/types/familleType';
import { Gateways, GatewaysRequest, GatewaysResponse } from '@/types/gateways';
import { Commercial, CommercialRequest } from '@/types/commercialType';
import { Societe } from '@/types/societeType';
import { EntrepriseResponse } from '@/types/entreprise';
import { ComptesResponse, DeviseResponse, EncaissementResponse, ModeResponse, ReglementPostResponse, ReglementRequest, ReglementsIdResponse, reglementsResponse, TauxResponse, TresorerieResponse } from '@/types/reglementType';



export const sageService = {

  // ========== Authentification ==========
   async authMe(): Promise<UserInterface> {
    return (await apiService.get(`${API_ENDPOINTS.auth}`)).data
  },

  async login(data: loginInterface): Promise<loginResponseInterface> {
    const rep = await apiService.post(`${API_ENDPOINTS.login}`, data)
    return rep.data
  },



  async forgotPass(email: string): Promise<responseDefault> {
    return (await apiService.post(`${API_ENDPOINTS.forgotPassword}`, { email: email })).data
  },

  async resetPass(data: resetPassInterface): Promise<responseDefault> {
    return (await apiService.post(`${API_ENDPOINTS.resetPassword}`, data)).data
  },

  // ========== contacts ==========
  async contacts(numero: string): Promise<Contacts[]> {
    return (await apiService.get(`${API_ENDPOINTS.contactsClient(numero)}`)).data
  },

  async addContact(data: ContactRequest): Promise<Contacts>{
      return (await apiService.post(API_ENDPOINTS.contactsClient(data.numero!), data)).data
  },

  async updateContact(contact_numero: number,data: ContactRequest): Promise<Contacts> {
    return (await apiService.put(API_ENDPOINTS.contactId(data.numero!, contact_numero), data)).data;
  },


  // ========== contacts ==========
  async searchEntreprise(query: string): Promise<EntrepriseResponse> {
    return (await apiService.get(`${API_ENDPOINTS.searchEntreprise(query)}`)).data
  },




  // ========== contacts ==========
  async commercials(): Promise<Commercial[]> {
    return (await apiService.get(`${API_ENDPOINTS.commercials}`)).data
  },

  async commercialsById(numero: string): Promise<Commercial> {
    return (await apiService.get(`${API_ENDPOINTS.commercialsById(numero)}`)).data
  },

  async addCommercial(data: CommercialRequest): Promise<Commercial> {
    return (await apiService.post(API_ENDPOINTS.commercials, data)).data
  },

  // async updateCommercial(contact_numero: number,data: ContactRequest): Promise<Commercial> {
  //   return (await apiService.put(API_ENDPOINTS.contactId(data.numero!, contact_numero), data)).data;
  // },




  // ========== clients ==========

  async getClients(query?: string): Promise<Client[]> {
    const params = query ? `?query=${encodeURIComponent(query)}` : ''
    return (await apiService.get(`${API_ENDPOINTS.clients}${params}`)).data
  },

  async getClient(id: string): Promise<Client> {
    return (await apiService.get<Client>(API_ENDPOINTS.clientById(id))).data
  },

  async addClient(data: ClientRequest): Promise<ClientCreateResponse> {
    return (await apiService.post(API_ENDPOINTS.clients, data)).data
  },

  async updateClient(numero: string, data: ClientUpdateRequest): Promise<Client> {
    return (await apiService.put(API_ENDPOINTS.clientById(numero), data)).data
  },

  async updateStatusClient(numero: string, est_actif: boolean): Promise<Client> {
    const data = {
      est_actif
    }
    return (await apiService.put(API_ENDPOINTS.clientById(numero), data)).data
  },



  
  // ========== societe ==========
  async getSociete(): Promise<Societe> {
    return (await apiService.get(`${API_ENDPOINTS.societe}`)).data
  },


  // ========== gateways ==========

  async getGateways(): Promise<GatewaysResponse> {
    return (await apiService.get(`${API_ENDPOINTS.gateways}`)).data
  },

  async getGatewaysById(id: string): Promise<Gateways> {
    return (await apiService.get<Gateways>(API_ENDPOINTS.gatewaysById(id))).data
  },

  async addGateways(data: GatewaysRequest): Promise<Gateways> {
    return (await apiService.post(API_ENDPOINTS.gateways, data)).data
  },



  // ========== Fournisseurs ==========

  async getFournisseurs(query?: string): Promise<Fournisseur[]> {
    const params = query ? `?query=${encodeURIComponent(query)}` : ''
    return (await apiService.get(`${API_ENDPOINTS.fournisseurs}${params}`)).data
  },

  async addFournisseur(data: FournisseurRequest): Promise<Fournisseur> {
    return (await apiService.post(API_ENDPOINTS.fournisseurs, data)).data
  },

  async updateFournisseur(numero: string, data: FournisseurUpdateRequest): Promise<Fournisseur> {
    return (await apiService.put(API_ENDPOINTS.fournisseursById(numero), data)).data
  },



  // ========== article ==========
  async getArticles(query?: string): Promise<Article[]> {
    const params = query ? `?query=${encodeURIComponent(query)}` : ''
    return (await apiService.get<Article[]>(`${API_ENDPOINTS.articles}${params}`)).data
  },

  async getArticleId(id: string): Promise<Article> {
    return (await apiService.get<Article>(API_ENDPOINTS.articleById(id))).data
  },

  async createArticle(data: ArticleRequest): Promise<Article> {
    const rep = await apiService.post<Article>(API_ENDPOINTS.articles, data)
    return rep.data
  },

  async updateArticle(reference: string, data: ArticleUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.articleById(reference), data)).data
  },



  // ========== add stock ==========
  async addStock(data: StockRequest): Promise<StockResponse> {
    const rep = await apiService.post<StockResponse>(API_ENDPOINTS.addStock, data)
    return rep.data
  },



  // ========== famille-article ==========

  async getFamilles(query?: string): Promise<Famille[]> {
    const params = query ? `?query=${encodeURIComponent(query)}` : ''
    return (await apiService.get(`${API_ENDPOINTS.familles}${params}`)).data
  },

  async createFamille(data: FamilleRequest): Promise<Famille> {
    return (await apiService.post(API_ENDPOINTS.familles, data)).data
  },




  // ========== devis ==========
  async getDevis(id: string): Promise<DevisListItem> {
    return (await apiService.get<DevisListItem>(API_ENDPOINTS.devisById(id))).data
  },

  async createDevis(data: DevisRequest): Promise<DevisResponse> {
    const rep = await apiService.post<DevisResponse>(API_ENDPOINTS.devis, data)
    return rep.data
  },

  async updateDevis(numero: string, data: DevisUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.devisById(numero), data)).data
  },

  async getDevisList(statut?: number, limit?: number): Promise<DevisListItem[]> {
    let params = ''

    if (statut !== undefined || limit) {
      const queryParams = new URLSearchParams()

      if (statut !== undefined) queryParams.append('statut', statut.toString())
      if (limit) queryParams.append('limit', limit.toString())
      params = `?${queryParams.toString()}`
    }

    return (await apiService.get<DevisListItem[]>(`${API_ENDPOINTS.devis}${params}`)).data
  },

  async changerStatut(type_doc: SageDocumentType, data: StatusRequest): Promise<StatusResponse> {
    return (await apiService.put(`/document/${type_doc}/${data.numero}/statut?nouveau_statut=${data.status}`)).data
  },




  async devisToPDF(id: string) {
    const response = await fetch(`${BackUrl}/devis/${id}/pdf`, {
      method: 'GET',
      headers: {
        'Accept': 'application/pdf',
      },
    });

    if (!response.ok) {
      throw new Error('Erreur lors du téléchargement');
    }

    // ✅ Récupérer directement en tant que Blob
    const blob = await response.blob();
    return blob;

  },


  // ========== commandes ==========
  async getCommandes(statut?: number, limit?: number): Promise<Commande[]> {
    let params = ''

    if (statut !== undefined || limit) {
      const queryParams = new URLSearchParams()

      if (statut !== undefined) queryParams.append('statut', statut.toString())
      if (limit) queryParams.append('limit', limit.toString())
      params = `?${queryParams.toString()}`
    }

    return (await apiService.get<Commande[]>(`/commandes${params}`)).data
  },

  async getCommande(id: string): Promise<Commande> {
    return (await apiService.get<Commande>(`/commandes/${id}`)).data
  },

  async createCommande(data: CommandeRequest): Promise<CommandeResponse> {
    const rep = await apiService.post<CommandeResponse>(API_ENDPOINTS.commandes, data)
    return rep.data
  },

  async updateCommande(numero: string, data: CommandeUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.commandeById(numero), data)).data
  },




  // ========== bon de livraison ==========
  async getAllBL(statut?: number, limit?: number): Promise<BL[]> {
    let params = ''

    if (statut !== undefined || limit) {
      const queryParams = new URLSearchParams()

      if (statut !== undefined) queryParams.append('statut', statut.toString())
      if (limit) queryParams.append('limit', limit.toString())
      params = `?${queryParams.toString()}`
    }
    const rep = await apiService.get<BL[]>(`${API_ENDPOINTS.bl}${params}`)
    return rep.data
  },

  async getBL(id: string): Promise<BL> {
    return (await apiService.get<BL>(`${API_ENDPOINTS.blById(id)}`)).data
  },

  async createBL(data: BLRequest) {
    const rep = await apiService.post(API_ENDPOINTS.bl, data)
    return rep.data
  },

  async updateBL(numero: string, data: BLUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.blById(numero), data)).data
  },





  // ========== Facture==========

  async getFactures(statut?: number, limit?: number): Promise<Facture[]> {
    let params = ''

    if (statut !== undefined || limit) {
      const queryParams = new URLSearchParams()

      if (statut !== undefined) queryParams.append('statut', statut.toString())
      if (limit) queryParams.append('limit', limit.toString())
      params = `?${queryParams.toString()}`
    }

    return (await apiService.get<Facture[]>(`${API_ENDPOINTS.factures}${params}`)).data
  },

  async getFacture(id: string): Promise<Facture> {
    return (await apiService.get<Facture>(`${API_ENDPOINTS.factures}/${id}`)).data
  },

  async relancerFacture(data: RelanceRequest): Promise<RelanceResponse> {
    return apiService.post(`${API_ENDPOINTS.factureRelancer(data.factureId)}`, {
      doc_id: data.factureId,
      message_personnalise: data.messagePersonnalise
    })
  },

  async createFacture(data: FactureRequest) {
    const rep = await apiService.post(API_ENDPOINTS.factures, data)
    return rep.data
  },

  async updateFacture(numero: string, data: FactureUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.factureById(numero), data)).data
  },

  async validerFacture(id: string): Promise<FactureValideResponse> {
    return (await apiService.post<FactureValideResponse>(API_ENDPOINTS.factureValider(id))).data
  },



  // ========== Avoirs ==========

  async getAvoirs(statut?: number, limit?: number): Promise<Avoir[]> {
    let params = ''

    if (statut !== undefined || limit) {
      const queryParams = new URLSearchParams()

      if (statut !== undefined) queryParams.append('statut', statut.toString())
      if (limit) queryParams.append('limit', limit.toString())
      params = `?${queryParams.toString()}`
    }

    return (await apiService.get<Avoir[]>(`${API_ENDPOINTS.avoirs}${params}`)).data
  },

  async getAvoir(id: string): Promise<Avoir> {
    return (await apiService.get<Avoir>(`${API_ENDPOINTS.avoirsById(id)}`)).data
  },

  async createAvoir(data: AvoirRequest) {
    const rep = await apiService.post(API_ENDPOINTS.avoirs, data)
    return rep.data
  },

  async updateAvoir(numero: string, data: AvoirUpdateRequest) {
    return (await apiService.put(API_ENDPOINTS.avoirsById(numero), data)).data
  },



  // ========== workflow ==========
  async devisToCommande(id: string): Promise<TransformationResponse> {
    return (await apiService.post<TransformationResponse>(API_ENDPOINTS.devisToCommande(id))).data
  },

  async devisToFacture(id: string): Promise<TransformationResponse> {
    return (await apiService.post<TransformationResponse>(API_ENDPOINTS.devisToFacture(id))).data
  },

  async commandeToBL(id: string): Promise<TransformationResponse> {
    return (await apiService.post<TransformationResponse>(API_ENDPOINTS.commandeToBL(id))).data
  },

  async commandeToFacture(id: string): Promise<TransformationResponse> {
    return (await apiService.post<TransformationResponse>(API_ENDPOINTS.commandeToFacture(id))).data
  },

  async blToFacture(id: string): Promise<TransformationResponse> {
    return (await apiService.post<TransformationResponse>(API_ENDPOINTS.blToFacture(id))).data
  },



  // ========== trans PDF ==========
  async transPDF(data: pdfInterface) {
    const response = await fetch(`${BackUrl}/documents/${data.type_doc}/${data.numero}/pdf`, {
      method: 'GET',
      headers: {
        'Accept': 'application/pdf',
      },
    });

    if (!response.ok) {
      throw new Error('Erreur lors du téléchargement');
    }

    // ✅ Récupérer directement en tant que Blob
    const blob = await response.blob();
    return blob;

  },


  async envoyerDevisSignature(id: string, emailSignataire: string, nomSignataire: string): Promise<any> {
    const request: SignatureRequest = {  
      sage_document_id: id,
      sage_document_type: TypeDocument.DEVIS,
      signer_email: emailSignataire,
      signer_name: nomSignataire,
      document_name: "test"
    }

    // return apiService.post(`/signature/universign/send`, request)
    return (await apiService.post(`/universign/signatures/create`, request)).data
  },


  async universign(): Promise<UniversignType[]> {
    return (await apiService.get(`/universign/transactions`)).data
  },

   async universignId(transaction_id: string): Promise<UniversignType> {
    return (await apiService.get<UniversignType>(`/universign/transactions/${transaction_id}`)).data
  },

  async downloadSignedDocument(transactionId: string): Promise<Blob> {
    const response = await apiService.get<Blob>(
      API_ENDPOINTS.downloadSignedDocument(transactionId),
      {
        responseType: 'blob',
        headers: {
          'Accept': 'application/pdf',
        },
      }
    );
    return response.data;
  },




  // ========== reglement ==========
  async getReglement(): Promise<reglementsResponse> {
    return (await apiService.get<reglementsResponse>(API_ENDPOINTS.reglement)).data
  },
  
  async getReglementId(id: string): Promise<ReglementsIdResponse> {
    return (await apiService.get<ReglementsIdResponse>(API_ENDPOINTS.reglementById(id))).data
  },


  async reglerFacture(data: ReglementRequest): Promise<ReglementPostResponse> {
    const rep = await apiService.post<ReglementPostResponse>(API_ENDPOINTS.reglerFacture, data)
    return rep.data
  },


  async getMode(): Promise<ModeResponse> {
    return (await apiService.get<ModeResponse>(API_ENDPOINTS.mode)).data
  },

  async getDevises(): Promise<DeviseResponse> {
    return (await apiService.get<DeviseResponse>(API_ENDPOINTS.devises)).data
  },

  async getTresorerie(): Promise<TresorerieResponse> {
    return (await apiService.get<TresorerieResponse>(API_ENDPOINTS.tresorerie)).data
  },

  async getCompteGeneraux(): Promise<ComptesResponse> {
    return (await apiService.get<ComptesResponse>(API_ENDPOINTS.compte_generaux)).data
  },

  async getTaux(): Promise<TauxResponse> {
    return (await apiService.get<TauxResponse>(API_ENDPOINTS.taux)).data
  },

  async getEncaissement(): Promise<EncaissementResponse> {
    return (await apiService.get<EncaissementResponse>(API_ENDPOINTS.encaissement)).data
  },

}
