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

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

const tahunanA1Api = () => {};

// API untuk get list table
tahunanA1Api.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 };
};

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

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

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

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