import { formatDate } from '@/lib/helper';
import { BaseApiService } from '@/services/api/base';
import { httpClient, httpClientFetcher } from '@/services/http/client';
import { BaseApiResponse } from '@/types/api/api-general';
import {
  ReportDepreciation,
  ReportDepreciationV2Item,
  ReportExpense,
} from '@/types/api/report/report-expense';

export class ReportExpenseApiService extends BaseApiService<
  ReportExpense,
  unknown,
  unknown
> {
  constructor(basePath: string) {
    super(basePath);
  }

  async getAllFetcher(
    endpoint: string
  ): Promise<BaseApiResponse<ReportExpense[]>> {
    return await httpClientFetcher<BaseApiResponse<ReportExpense[]>>(endpoint);
  }

  async exportToExcel(initialQueryString: string) {
    const params = new URLSearchParams(initialQueryString);

    params.set('export', 'excel');
    params.set('type', 'all');
    params.set('page', '1');
    params.set('limit', '99999999999');

    const queryString = `?${params.toString()}`;

    const res = await httpClient<Blob>(`${this.basePath}${queryString}`, {
      method: 'GET',
      responseType: 'blob',
    });

    const url = window.URL.createObjectURL(new Blob([res]));
    const link = document.createElement('a');
    link.href = url;

    const fileName = `Laporan-BOP-${formatDate(Date.now(), 'DD-MM-YYYY')}.xlsx`;
    link.setAttribute('download', fileName);

    document.body.appendChild(link);
    link.click();
    link.remove();
  }
}

export const ReportExpenseApi = new ReportExpenseApiService('/reports/expense');

export const DepreciationReportApi = new BaseApiService<
  ReportDepreciation,
  unknown,
  unknown
>('/reports/expense/depreciation');

export const DepreciationReportV2Api = new BaseApiService<
  ReportDepreciationV2Item,
  unknown,
  unknown
>('/reports/expense/v2/depreciation');
