import type {
  TableReturFakturPKResult,
  TBaseResponseAPI,
  TCancelReturPKRequest,
  TPrepopulatedReturPKRequest,
} from '../types/types';

import unifikasiClient from './unifikasiClient';

const fakturApi = () => {};

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

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

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

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

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

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

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

  return dnData;
};

fakturApi.prepopulatedReturPK = async (payload: TPrepopulatedReturPKRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_005/rpk', payload);

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

  return data;
};

fakturApi.cancelReturPK = async (payload: TCancelReturPKRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_005/batal', payload);
  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('Cancel Retur PK failed:', { statusCode, status, message });
    throw new Error(message || 'Gagal mengcancel Retur pajak Keluaran');
  }

  return data;
};

export default fakturApi;
