import axios from 'axios';
import type {
  TBaseResponseAPI,
  TCancelRequest,
  TCancelResponse,
  TGetListDataTableFakturPMResult,
  TPrepopulatedPMRequest,
  TUploadFakturPMRequest,
  TValidateFakturPMRequest,
} from '../types/types';

import unifikasiClient from './unifikasiClient';
import { normalizePayloadCetakPdfDetail } from './normalizePayloadCetakPdf';

const fakturApi = () => {};

const axiosCetakPdf = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API_URL_CETAK,
  headers: {
    Authorization: `Basic ${window.btoa('admin:ortax123')}`,
    password: '',
  },
});

// API untuk get list table
fakturApi.getFakturPM = async (config: any) => {
  const {
    data: { message, metaPage, data },
    status: statusCode,
  } = await unifikasiClient.get<TBaseResponseAPI<TGetListDataTableFakturPMResult>>('/IF_TXR_015', {
    ...config,
  });

  if (statusCode !== 200) {
    throw new Error(message);
  }

  return { total: metaPage ? Number(metaPage.totalRow) : 0, data };
};

fakturApi.getFakturPMById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_015', { params: { id } });

  const {
    data: { status, message, data },
    status: statusCode,
  } = res;

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('getFakturPM failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal mengambil data FakturPM');
  }

  const dnData = Array.isArray(data) ? data[0] : data;

  return dnData;
};

fakturApi.confirmationWaitingFakturPM = async (payload: TValidateFakturPMRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_062', payload);

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('validateFakturPM failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal memvalidasi Faktur Pajak');
  }

  return data;
};

fakturApi.uploadPMPrepop = async (payload: TUploadFakturPMRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_015/upload', payload);
  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('validateFakturPM failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal memvalidasi Faktur Pajak');
  }

  return data;
};

fakturApi.cetakPdfDetail = async (payload: { id: string }) => {
  // 1️⃣ Ambil data faktur dari Unifikasi
  const fakturRaw = await fakturApi.getFakturPMById(payload.id);

  console.log();

  // 2️⃣ Normalize agar sesuai format yang dibutuhkan API cetak PDF
  const payloadCetak = normalizePayloadCetakPdfDetail(fakturRaw);

  // 3️⃣ Call API PDF
  const response = await axiosCetakPdf.post('/report/ctas/faktur/pk', payloadCetak);
  const body = response.data;

  // 4️⃣ Validasi response
  if (
    !response ||
    response.status !== 200 ||
    body.status === 'fail' ||
    body.status === 'error' ||
    body.status === '0'
  ) {
    throw new Error(
      body.message || 'System tidak dapat memenuhi permintaan, coba beberapa saat lagi'
    );
  }

  return body;
};

fakturApi.prepopulatedPM = async (payload: TPrepopulatedPMRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_015/prepopulated', payload);

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('prepopulatedPM failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal melakukan prepopulated Faktur PM');
  }

  return data;
};

fakturApi.cancel = async ({ id, revokeFlag }: TCancelRequest): Promise<TCancelResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_006', {
    id,
    revokeFlag,
  });

  console.log('Cancel Digunggung response:', { code, message, status });
  if (code === 0) {
    throw new Error(message || 'Gagal membatalkan data');
  }

  return {
    status,
    message,
    data,
    code,
    time,
    metaPage,
    total,
  };
};

export default fakturApi;
