import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import {
  CreateProjectFlockPayload,
  ProjectFlock,
  UpdateProjectFlockPayload,
} from '@/types/api/production/project-flock';
import {
  CreateRecordingPayload,
  Recording,
  UpdateRecordingPayload,
  NextDayRecording,
} from '@/types/api/production/recording';
import { ProjectFlockKandang } from '@/types/api/production/project-flock-kandang';
import { httpClient } from '@/services/http/client';
import { formatDate } from '@/lib/helper';

export const ProjectFlockKandangApi = new BaseApiService<
  ProjectFlockKandang,
  unknown,
  unknown
>('/production/project-flock-kandangs');
export const ProjectFlockApi = new BaseApiService<
  ProjectFlock,
  CreateProjectFlockPayload,
  UpdateProjectFlockPayload
>('/production/project-flocks');
export class RecordingService extends BaseApiService<
  Recording,
  CreateRecordingPayload,
  UpdateRecordingPayload
> {
  constructor(basePath: string = '') {
    super(basePath);
  }

  async approve(
    idOrIds: number | number[],
    notes?: string
  ): Promise<BaseApiResponse<Recording[]> | undefined> {
    const approvable_ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
    return await this.customRequest<BaseApiResponse<Recording[]>>('approvals', {
      method: 'POST',
      payload: {
        action: 'APPROVED',
        approvable_ids,
        notes,
      },
    });
  }

  async reject(
    idOrIds: number | number[],
    notes: string = ''
  ): Promise<BaseApiResponse<Recording[]> | undefined> {
    const approvable_ids = Array.isArray(idOrIds) ? idOrIds : [idOrIds];
    return await this.customRequest<BaseApiResponse<Recording[]>>('approvals', {
      method: 'POST',
      payload: {
        action: 'REJECTED',
        approvable_ids,
        notes,
      },
    });
  }

  async deleteGrading(
    gradingId: number
  ): Promise<BaseApiResponse<unknown> | undefined> {
    return await this.customRequest<BaseApiResponse<unknown>>(
      `gradings/${gradingId}`,
      {
        method: 'DELETE',
      }
    );
  }

  async nextDayRecording(
    projectFlockId: number,
    recordDate?: string
  ): Promise<BaseApiResponse<NextDayRecording> | undefined> {
    return await this.customRequest<BaseApiResponse<NextDayRecording>>(
      `next-day`,
      {
        method: 'GET',
        params: {
          project_flock_kandang_id: projectFlockId,
          record_date: recordDate,
        },
      }
    );
  }

  async exportToExcel(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 = `recording-${formatDate(Date.now(), 'DD-MM-YYYY')}.xlsx`;
    link.setAttribute('download', fileName);

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

  async exportInputProgressToExcel(startDate: string, endDate: string) {
    const params = new URLSearchParams();

    params.set('export', 'excel');
    params.set('type', 'progress');
    params.set('start_date', formatDate(startDate, 'YYYY-MM-DD'));
    params.set('end_date', formatDate(endDate, 'YYYY-MM-DD'));

    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 = `input-progres-recording-${formatDate(startDate, 'DD-MM-YYYY')}-ke-${formatDate(endDate, 'DD-MM-YYYY')}.xlsx`;
    link.setAttribute('download', fileName);

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

export const RecordingApi = new RecordingService('/production/recordings');
