import axios from 'axios';
import fetchAdapter from '@vespaiach/axios-fetch-adapter';

const S3_API_URL = 'https://s3-store-api.autoshopee.com';

const S3_BUCKET = {
  ORDER_PRINT: 'order-print',
};

const autoshopeeS3Client = axios.create({
  adapter: fetchAdapter,
  baseURL: S3_API_URL,
  timeout: 60000,
});

autoshopeeS3Client.interceptors.response.use((response) => {
  return response.data;
});

export const getS3FileUrl = (filePath) => `${S3_API_URL}/${filePath}`;

/**
 * @param {ArrayBuffer} buffer
 * @param {string} fileName
 * @param {Record<string, string>} metadataPayload
 * @returns {Promise<import('@type/AutoShopee/Service/S3').S3UploadResult>}
 */
export const uploadS3OrderPrintPdf = async (buffer, fileName, metadataPayload = {}) => {
  const filePath = `${S3_BUCKET.ORDER_PRINT}/${fileName}`;

  const metadataHeaders = Object.entries(metadataPayload).reduce((acc, [key, value]) => {
    if (value === undefined || value === null) {
      return acc;
    }

    if (key.startsWith('x-amz-meta-')) {
      acc[key] = value;
      return acc;
    }

    acc[`x-amz-meta-${key}`] = value;
    return acc;
  }, {});

  await autoshopeeS3Client.put(filePath, buffer, {
    headers: {
      'Content-Type': 'application/pdf',
      ...metadataHeaders,
    },
    responseType: 'text',
  });

  return {
    fileId: filePath,
    fileUrl: getS3FileUrl(filePath),
  };
};

export {
  autoshopeeS3Client,
};
