import axios from 'axios';
import type {
  TBaseResponseAPI,
  TCancelNrRequest,
  TCancelNrResponse,
  TDeleteNrRequest,
  TGetListDataTableNrResult,
  TPostBupot26Request,
} from '../types/types';

import unifikasiClient from './unifikasiClient';

const bupot21 = () => {};

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

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

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

bupot21.save = async (config: TPostBupot26Request) => {
  const {
    data: { message, data, code },
  } = await unifikasiClient.post<TBaseResponseAPI<TPostBupot26Request>>('/IF_TXR_029/', {
    ...config,
  });
  if (code === 0) {
    throw new Error(message);
  }

  return data;
};

bupot21.getById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_029/', { params: { id, feature: '26' } });

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

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

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

  return dnData;
};

bupot21.upload = async ({ id }: { id: string | number }) => {
  const {
    data: { status, message, data, code },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_029/upload', { id, feature: '26' });

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

bupot21.delete = async (payload: TDeleteNrRequest, config?: Record<string, any>): Promise<any> => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post<TBaseResponseAPI<any>>('/IF_TXR_029/delete', payload, {
    ...config,
  });

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

  return data;
};

bupot21.cancel = async ({ id, tglPembatalan }: TCancelNrRequest): Promise<TCancelNrResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_029/batal', {
    id,
    tglPembatalan,
    feature: '26',
  });

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

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

bupot21.cetakPdfDetail = async (payload: Record<string, any>) => {
  const response = await axiosCetakPdf.post('/report/ctas/bpnr', 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 bupot21;
