import {Buffer} from 'buffer';

const fecher = async (url: string, token: string) => {
    return await fetch(url, {
      method: 'POST',
      
      headers: { 
        'Authorization' :token
      },      
    });
  }
  
  export const useBasicAuth = async (endpoint: string, username:string, password: string) => {
    //url=  process.env.API_URL+url;
    const token = 'Basic '+ Buffer.from(username + ':' + password).toString('base64');
    let data;
    let error;
    try{
        const url = process.env.API_URL + endpoint; 
      
        const response = await fecher(url, token)
      
        if (response.ok){
          const token = response.headers.get('Authorization') ;
          if (token){
            data = token.replaceAll("Basic ","")
          }
        }else {
          const trace = await response.json();
          error = "Servidor: "+ trace.message;
        }
    }catch (trace){
      error = "Cliente: "+trace;
    }
    return {
      data,
      error
    }
  
  }