import type {
  TBaseResponseAPI,
  TCancelRequest,
  TCancelResponse,
  TDeleteRequest,
  TGetListDataDokumenLainKeluaranResult,
  TGoodsResult,
  TIdTambahanResult,
  TKeteranganTambahanResult,
  TPostDokumenLainKeluaranRequest,
  TReturDokumenRequest,
  TReturDokumenResponse,
  TSatuanResult,
  TServiceResult,
} from '../types/types';

import unifikasiClient from './unifikasiClient';

const fakturApi = () => {};

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

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

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

fakturApi.getIdTambahan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TIdTambahanResult>>(
    '/sandbox/mst_faktur_idtambahan',
    {
      params,
    }
  );

  const body = response.data;

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

  return body;
};

fakturApi.getKeteranganTambahan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TKeteranganTambahanResult>>(
    '/sandbox/mst_faktur_keterangan',
    {
      params,
    }
  );

  const body = response.data;

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

  return body;
};

fakturApi.saveDokumenLainKeluaran = async (config: TPostDokumenLainKeluaranRequest) => {
  const {
    data: { message, data, code },
  } = await unifikasiClient.post<TBaseResponseAPI<TPostDokumenLainKeluaranRequest>>(
    '/IF_TXR_009/dk',
    {
      ...config,
    }
  );
  if (code === 0) {
    throw new Error(message);
  }

  return data;
};

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

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

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

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

  return dnData;
};

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

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

fakturApi.deleteDokumenLainKeluaran = async (
  payload: TDeleteRequest,
  config?: Record<string, any>
): Promise<any> => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post<TBaseResponseAPI<any>>('/IF_TXR_009/dk/delete', payload, {
    ...config,
  });

  if (statusCode !== 200 || status?.toLowerCase() === 'error') {
    throw new Error(message || 'Gagal menghapus data Faktur PK');
  }

  return data;
};

fakturApi.cancelDokumenLainKeluaran = async ({ id }: TCancelRequest): Promise<TCancelResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_012', {
    id,
    isCreatedByBuyer: false,
  });

  console.log('Cancel Dokumen Lain Keluaran response:', { code, message, status });
  if (code === 0) {
    throw new Error(message || 'Gagal membatalkan data');
  }

  return {
    status,
    message,
    data,
    code,
    time,
    metaPage,
    total,
  };
};

fakturApi.getGoods = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TGoodsResult>>('/sandbox/mst_goods', {
    params,
  });

  const body = response.data;

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

  return body;
};

fakturApi.getServices = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TServiceResult>>(
    '/sandbox/mst_services',
    {
      params,
    }
  );

  const body = response.data;

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

  return body;
};

fakturApi.getSatuan = async (params?: Record<string, any>) => {
  const response = await unifikasiClient.get<TBaseResponseAPI<TSatuanResult>>(
    '/sandbox/mst_satuan',
    {
      params,
    }
  );

  const body = response.data;

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

  return body;
};

fakturApi.returDokumenLainKeluaran = async (
  payload: TReturDokumenRequest
): Promise<TReturDokumenResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_079', payload);

  console.log('Retur Dokumen Lain Keluaran response:', { code, message, status });

  if (code === 0) {
    throw new Error(message || 'Gagal melakukan retur dokumen');
  }

  return {
    status,
    message,
    data,
    code,
    time,
    metaPage,
    total,
  };
};

export default fakturApi;
