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

import unifikasiClient from './unifikasiClient';

const nrApi = () => {};

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
nrApi.getNr = 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 };
};

nrApi.getKodeObjekPajakNr = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TGetListDataKOPNrResult>>(
    '/sandbox/mst_kop_bpnr',
    { params }
  );

  const body = response.data;

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

  return body;
};

nrApi.getCountryNr = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TCountryResult>>(
    '/sandbox/mst_negara',
    { params }
  );

  const body = response.data;

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

  return body;
};

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

  return data;
};

nrApi.getNrById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_029/', { params: { id } });

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

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

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

nrApi.deleteNr = 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;
};

nrApi.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,
  });

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

nrApi.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 nrApi;
