import apiClient from "../api-client";

/**
 * MPT 참조값 인터페이스
 */
export interface MptReferenceRange {
  key: string;
  name: string;
  upperLimit: number | null;
  lowerLimit: number | null;
  unit: string;
  category: 'energy' | 'protein' | 'liver' | 'mineral' | 'etc';
  categoryName: string;
  description?: string;
}

/**
 * MPT 카테고리 인터페이스
 */
export interface MptCategory {
  key: string;
  name: string;
  color: string;
  items: string[];
}

/**
 * MPT 참조값 응답
 */
export interface MptReferenceResponse {
  references: Record<string, MptReferenceRange>;
  categories: MptCategory[];
}

/**
 * MPT 통계 응답 DTO
 */
export interface MptStatisticsDto {
  totalMptCows: number;
  latestTestDate: string | null;
  categories: {
    energy: { safe: number; caution: number };
    protein: { safe: number; caution: number };
    liver: { safe: number; caution: number };
    mineral: { safe: number; caution: number };
  };
  riskyCows: Array<{
    cowId: string;
    category: string;
    itemName: string;
    value: number;
    status: 'high' | 'low';
  }>;
}

/**
 * MPT(혈액화학검사) 결과 DTO
 */
export interface MptDto {
  pkMptNo: number;
  cowShortNo: string;
  fkFarmNo: number;
  testDt: string;
  monthAge: number;
  milkYield: number;
  parity: number;
  // 에너지 대사
  glucose: number;
  cholesterol: number;
  nefa: number;
  bcs: number;
  // 단백질 대사
  totalProtein: number;
  albumin: number;
  globulin: number;
  agRatio: number;
  bun: number;
  // 간기능
  ast: number;
  ggt: number;
  fattyLiverIdx: number;
  // 미네랄
  calcium: number;
  phosphorus: number;
  caPRatio: number;
  magnesium: number;
  creatine: number;
  // Relations
  farm?: {
    pkFarmNo: number;
    farmerName: string;
  };
}

/**
 * MPT(혈액화학검사) 관련 API
 */
export const mptApi = {
  /**
   * GET /mpt?cowShortNo=:cowShortNo - 특정 개체의 검사 결과 (뒤 4자리)
   */
  findByCowShortNo: async (cowShortNo: string): Promise<MptDto[]> => {
    return await apiClient.get("/mpt", {
      params: { cowShortNo },
    });
  },

  /**
   * GET /mpt?cowId=:cowId - 특정 개체의 검사 결과 (전체 개체번호)
   */
  findByCowId: async (cowId: string): Promise<MptDto[]> => {
    return await apiClient.get("/mpt", {
      params: { cowId },
    });
  },

  /**
   * GET /mpt/statistics/:farmNo - 농장별 MPT 통계 조회
   */
  getMptStatistics: async (farmNo: number): Promise<MptStatisticsDto> => {
    return await apiClient.get(`/mpt/statistics/${farmNo}`);
  },

  /**
   * GET /mpt/reference - MPT 참조값 조회
   */
  getReferenceValues: async (): Promise<MptReferenceResponse> => {
    return await apiClient.get("/mpt/reference");
  },
};
