import type {
  TBaseResponseAPI,
  TCancelRequest,
  TCancelResponse,
  TDeleteRequest,
  TGetListDataDokumenLainMasukanResult,
  TGoodsResult,
  TIdTambahanResult,
  TKeteranganTambahanResult,
  TPostCreditUncreditedRequest,
  TPostDokumenLainMasukanRequest,
  TPrepopulatedDokumenLainMasukanRequest,
  TRequestDokumenLainMasukanPrep,
  TReturDokumenMasukanRequest,
  TReturDokumenMasukanResponse,
  TSatuanResult,
  TServiceResult,
} from '../types/types';

import unifikasiClient from './unifikasiClient';

const fakturApi = () => {};

// API untuk get list table
fakturApi.getDokumenLainMasukan = async (config: any) => {
  const {
    data: { message, metaPage, data },
    status: statusCode,
  } = await unifikasiClient.get<TBaseResponseAPI<TGetListDataDokumenLainMasukanResult>>(
    '/IF_TXR_009/dm',
    {
      ...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.saveDokumenLainMasukan = async (config: TPostDokumenLainMasukanRequest) => {
  const {
    data: { message, data, code },
  } = await unifikasiClient.post<TBaseResponseAPI<TPostDokumenLainMasukanRequest>>(
    '/IF_TXR_009/dm',
    {
      ...config,
    }
  );
  if (code === 0) {
    throw new Error(message);
  }

  return data;
};

fakturApi.getDokumenLainMasukanById = async (id: string) => {
  const res = await unifikasiClient.get('/IF_TXR_009/dm', { 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 Masukan');
  }

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

  return dnData;
};

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

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

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

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

  return data;
};

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

  console.log('Cancel Dokumen Lain Masukan 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.returDokumenLainMasukan = async (
  payload: TReturDokumenMasukanRequest
): Promise<TReturDokumenMasukanResponse> => {
  const {
    data: { status, message, data, code, time, metaPage, total },
  } = await unifikasiClient.post('/IF_TXR_082', payload);

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

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

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

fakturApi.prepopulatedDokumenLainMasukan = async (
  payload: TPrepopulatedDokumenLainMasukanRequest
) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_016/prepopulated', payload);

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

  return data;
};

fakturApi.postCreditUncredited = async (payload: TPostCreditUncreditedRequest) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_016/upload', payload);

  if (statusCode !== 200 || status?.toLowerCase() !== 'success') {
    console.error('postCreditUncredited failed:', {
      statusCode,
      status,
      message,
    });
    throw new Error(message || 'Gagal melakukan credit / uncredited dokumen');
  }

  return data;
};

fakturApi.prepopulatedDokumenLainMasukan = async (payload: TRequestDokumenLainMasukanPrep) => {
  const {
    data: { status, message, data },
    status: statusCode,
  } = await unifikasiClient.post('/IF_TXR_016/prepopulated', payload);

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

  return data;
};

export default fakturApi;
