import {
  Chickin,
  CreateChickinPayload,
  UpdateChickinPayload,
} from '@/types/api/production/chickin';
import { BaseApiService } from '@/services/api/base';
import { BaseApiResponse } from '@/types/api/api-general';
import { httpClient } from '@/services/http/client';
import axios from 'axios';

export class ChickinService extends BaseApiService<
  Chickin,
  CreateChickinPayload,
  UpdateChickinPayload
> {
  constructor(basePath: string = '/production/chickins') {
    super(basePath);
  }

  async updateChickinDate(
    projectFlockKandangId: number,
    chickInDate: string
  ): Promise<BaseApiResponse<{ message: string }> | undefined> {
    try {
      return await httpClient<BaseApiResponse<{ message: string }>>(
        `${this.basePath}/chick-in-date`,
        {
          method: 'PATCH',
          body: {
            project_flock_kandang_id: projectFlockKandangId,
            chick_in_date: chickInDate,
          },
        }
      );
    } catch (error: unknown) {
      if (axios.isAxiosError<BaseApiResponse<{ message: string }>>(error)) {
        return error.response?.data;
      }
      return undefined;
    }
  }

  /**
   * Approve single marketing data
   */
  async singleApproval(
    id: number,
    action: 'APPROVED' | 'REJECTED',
    notes?: string
  ): Promise<BaseApiResponse<{ message: string }> | undefined> {
    try {
      const path = `${this.basePath}/approvals`;
      return await httpClient<BaseApiResponse<{ message: string }>>(path, {
        method: 'POST',
        body: {
          action: action,
          approvable_ids: [id],
          notes: notes ?? `${action} chickin ${id}`,
        },
      });
    } catch (error) {
      throw error;
    }
  }
}

export const ChickinApi = new ChickinService('/production/chickins');
