import { BaseApiService } from '@/services/api/base';
import { httpClient, httpClientFetcher } from '@/services/http/client';
import {
  DailyMarketingReport,
  DailyMarketingReportResponse,
} from '@/types/api/report/marketing';
import { formatDate } from '@/lib/helper';

export class MarketingReportApiService extends BaseApiService<
  DailyMarketingReport,
  unknown,
  unknown
> {
  constructor(basePath: string = '/reports/marketing') {
    super(basePath);
  }

  async getAllDailyMarketingFetcher(
    endpoint: string
  ): Promise<DailyMarketingReportResponse> {
    return await httpClientFetcher<DailyMarketingReportResponse>(endpoint);
  }

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

    params.set('export', 'excel');
    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-penjualan-harian-${formatDate(Date.now(), 'DD-MM-YYYY')}.xlsx`;
    link.setAttribute('download', fileName);

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

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

    params.set('export', 'pdf');
    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-penjualan-harian-${formatDate(Date.now(), 'DD-MM-YYYY')}.pdf`;
    link.setAttribute('download', fileName);

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

export const MarketingReportApi = new MarketingReportApiService(
  '/reports/marketing'
);
