import { apiRequest } from "@/utils/api/apiRequest"; import { isValidDate } from "@/helpers/Date"; export const listSchedule = async (startDate?: string, endDate?: string) => { const token = localStorage.getItem('token'); if (!token) { throw new Error('No token found in localStorage.'); } if (startDate && !isValidDate(startDate)) { throw new Error('Invalid start date'); } if (endDate && !isValidDate(endDate)) { throw new Error('Invalid end date'); } const params = new URLSearchParams(); if (startDate) params.append('start', startDate); if (endDate) params.append('end', endDate); const endpoint = `/api/schedule${params.toString() ? `?${params.toString()}` : ''}`; return apiRequest.get(endpoint, { headers: { Authorization: `Bearer ${token}`, } }) .then((scheduleData) => scheduleData?.payload?.schedule); }; export const getScheduleForDate = async (date: string) => { const token = localStorage.getItem('token'); if (!token) { throw new Error('No token found in localStorage.'); } if (!isValidDate(date)) { throw new Error('Invalid date'); } const endpoint = `/api/schedule/${date}`; return apiRequest.get(endpoint, { headers: { Authorization: `Bearer ${token}`, } }) .then((scheduleData) => scheduleData?.payload?.schedule) .catch((err) => { throw err; }); }; // Update the schedule for a specific date (e.g., mark as skipped) export const updateScheduleForDate = async (date: string, isSkipped: boolean) => { const token = localStorage.getItem('token'); if (!token) { throw new Error('No token found in localStorage.'); } if (!isValidDate(date)) { throw new Error('Invalid date'); } const endpoint = `/api/schedule/${date}`; return apiRequest.put(endpoint, { is_skipped: isSkipped }, { headers: { Authorization: `Bearer ${token}`, } }) .then((scheduleData) => scheduleData?.payload?.schedule) .catch((err) => { throw err; }); }; // Generate a new schedule (optional: overwrite the existing one) export const generateSchedule = async (overwrite: boolean) => { const token = localStorage.getItem('token'); if (!token) { throw new Error('No token found in localStorage.'); } const endpoint = `/api/schedule/generate`; return apiRequest.post(endpoint, { overwrite }, { headers: { Authorization: `Bearer ${token}`, } }) .then((scheduleData) => scheduleData?.payload?.schedule) .catch((err) => { throw err; }); }; export const scheduleUserDish = async (date: string, user_id: number, user_dish_id: number|null, skipped: boolean = false) => { const token = localStorage.getItem('token'); if (!token) throw new Error('No token found in localStorage.'); const endpoint = `/api/schedule/${date}/user-dishes`; return apiRequest.post(endpoint, { user_dish_id, user_id, skipped }, { headers: { Authorization: `Bearer ${token}`} }) .then((scheduleData) => scheduleData?.payload?.schedule) .catch((err) => { throw err }); };