import { fetcher, endpoints } from 'src/lib/axios-ctas-box';
import type {
  BupotRecord,
  TBaseResponseAPI,
  TGetListDataKOPBupotFinalResult,
  TGetListDataTableBupotFinalResult,
  TPortBulananCenceledRequest,
  TPortBulananRequest,
  TPostBupotFinalRequest,
} from '../types/types';

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

const finalTdkFinalApi = () => {};

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

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

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

// ✅ adjust biar bisa terima params
finalTdkFinalApi.getKodeObjekPajak = async (params?: Record<string, any>) => {
  const response = await fetcher<TBaseResponseAPI<TGetListDataKOPBupotFinalResult>>([
    '/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;
};

finalTdkFinalApi.save = async (config: TPostBupotFinalRequest) => {
  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;
};

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

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

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