import { fetcher, endpoints } from 'src/lib/axios-ctas-box';
import type {
  BupotRecord,
  TBaseResponseAPI,
  TGetListDataKOPDnResult,
  TGetListDataTableDnResult,
  TPortBulananCenceledRequest,
  TPortBulananRequest,
  TPostBulananRequest,
} from '../types/types';

const {list, canceled, delete: deleteAPI, upload} =  endpoints.pph21.bulanan

const bulananApi = () => {};

// API untuk get list table
bulananApi.getList = async (config: any) => {
  const response = await fetcher<TBaseResponseAPI<TGetListDataTableDnResult>>([
    list,
    {
      method: 'GET',
      ...config,
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to fetch bulanan data');
  }

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

// ✅ adjust biar bisa terima params
bulananApi.getKodeObjekPajak = async (params?: Record<string, any>) => {
  const response = await fetcher<TBaseResponseAPI<TGetListDataKOPDnResult>>([
    '/sandbox/mst_kop_bpu',
    {
      method: 'GET',
      params, // ⬅️ inject ke query string
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to fetch kode objek pajak');
  }

  return response;
};

bulananApi.save = async (config: TPostBulananRequest) => {
  const response = await fetcher<TBaseResponseAPI<BupotRecord[]>>([
    list,
    {
      method: 'POST',
      data: config,
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to save bulanan data');
  }

  return response.data;
};

bulananApi.upload = async (config: TPortBulananRequest) => {
  const response = await fetcher<TBaseResponseAPI<BupotRecord>>([
    upload,
    {
      method: 'POST',
      data: config,
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to upload bulanan data');
  }

  return response.data;
};

bulananApi.delete = async (config: TPortBulananRequest) => {
  const response = await fetcher<TBaseResponseAPI<BupotRecord>>([
    deleteAPI,
    {
      method: 'POST',
      data: config,
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to delete bulanan data');
  }

  return response.data;
};

bulananApi.batal = async (config: TPortBulananCenceledRequest) => {
  const response = await fetcher<TBaseResponseAPI<BupotRecord>>([
    canceled,
    {
      method: 'POST',
      data: config,
    },
  ]);

  if (!response || response.status !== 'success') {
    throw new Error(response?.message || 'Failed to delete bulanan data');
  }

  return response.data;
};

export default bulananApi;
