import axios from "axios";


const BASE_URL = "http://10.10.1.112:5000";

// ─── Types ────────────────────────────────────────────────────────────────────

export type EggGrade = "A" | "B" | "C" | "TL";
export type Period   = "today" | "week" | "month" | "all";

export interface GradeSummary {
  count: number;
  avgWeight: number;
}

export interface HistoryPoint {
  time: string;
  A: number;
  B: number;
  C: number;
  TL: number;
}

export interface SummaryResponse {
  gradeA: GradeSummary;
  gradeB: GradeSummary;
  gradeC: GradeSummary;
  gradeTL: GradeSummary;
  history: HistoryPoint[];
}

export interface EggRecord {
  id: number;
  timestamp: string;
  date: string;
  grade: EggGrade;
  weight: number;
}

export interface LatestDataResponse {
  berat: number;
  grade: EggGrade;
  timestamp: string;
}

// ─── Axios instance dengan timeout ───────────────────────────────────────────
const api = axios.create({
  baseURL: BASE_URL,
  timeout: 8000,
});

// ─── API Calls ────────────────────────────────────────────────────────────────


//Ambil semua data telur dari MySQL
 
export const getEggData = async (): Promise<EggRecord[]> => {
  const res = await api.get("/telur");
  return res.data;
};


 //Ambil data telur terbaru.

export const getLatestData = async (): Promise<LatestDataResponse> => {
  const res = await api.get("/latest");
  return res.data;
};

// Ringkasan per grade + history chart untuk dashboard.

export const getSummary = async (period: Period = "today"): Promise<SummaryResponse> => {
  const res = await api.get("/summary", { params: { period } });
  return res.data;
};

//Set kecepatan conveyor (0–255).
export const setConveyorSpeed = async (speed: number): Promise<void> => {
  await api.post("/setSpeed", { speed });
};

//Ambil kecepatan conveyor saat ini.

export const getConveyorSpeed = async (): Promise<number> => {
  const res = await api.get("/getSpeed");
  return res.data.speed;
};