import axios from 'axios';
import type {
  TBaseResponseAPI,
  TCancelDnRequest,
  TCancelDnResponse,
  TDeleteDnRequest,
  TGetListDataKOPDnResult,
  TGetListDataTableDnResult,
  TPostDnRequest,
} from '../types/types';

import unifikasiClient from './unifikasiClient';

const dnApi = () => {};

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
dnApi.getDn = async (config: any) => {
  const {
    data: { message, metaPage, data },
    status: statusCode,
  } = await unifikasiClient.get<TBaseResponseAPI<TGetListDataTableDnResult>>('IF_TXR_028/bpu', {
    ...config,
  });

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

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

dnApi.getKodeObjekPajakDn = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TGetListDataKOPDnResult>>(
    '/sandbox/mst_kop_bpu',
    { params }
  );

  const body = response.data;

  if (response.status !== 200 || body.status !== 'success') {
    throw new Error(body.message);
  }

  return body;
};

dnApi.saveDn = async (config: TPostDnRequest) => {
  const {
    data: { message, data, code },
    // status: statusCode,
  } = await unifikasiClient.post<TBaseResponseAPI<TPostDnRequest>>('/IF_TXR_028/bpu', {
    ...config,
  });
  if (code === 0) {
    throw new Error(message);
  }

  return data;
};

dnApi.getDnById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_028/bpu', { params: { id } });

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

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

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

  return dnData;
};

dnApi.upload = async ({ id }: { id: string | number }) => {
  const {
    data: { status, message, data, code },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_028/bpu/upload', { id });

  return { status, message, data, code, statusCode };
};

dnApi.deleteDn = async (payload: TDeleteDnRequest, config?: Record<string, any>): Promise<any> => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post<TBaseResponseAPI<any>>('/IF_TXR_028/bpu/delete', payload, {
    ...config,
  });

  if (statusCode !== 200 || status?.toLowerCase() === 'error') {
    throw new Error(message || 'Gagal menghapus data DN');
  }

  return data;
};

dnApi.cancel = async ({ id, tglPembatalan }: TCancelDnRequest): Promise<TCancelDnResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
    // status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_028/bpu/batal', {
    id,
    tglPembatalan,
  });

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

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

dnApi.cetakPdfDetail = async (payload: Record<string, any>) => {
  const response = await axiosCetakPdf.post('/report/ctas/bpu', payload);

  const body = response.data;

  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;
};

export default dnApi;
