import { api } from './api';

export interface CreateTrainingPlanDto {
  startDate: string;
  name?: string;
  mode: 'daysOfWeek' | 'sessionsPerWeek';
  daysOfWeek: number[];
  sessionsPerWeek: number;
  goal: string;
  startWeightKg?: number;
  preferredTimeOfDay?: 'morning' | 'noon' | 'evening' | '';
}

export type PlanMode = 'daysOfWeek' | 'sessionsPerWeek';

export type PlanGoal =
  | 'postpartum_recovery' // 产后恢复
  | 'fat_loss' // 减脂塑形
  | 'posture_correction' // 体态矫正
  | 'core_strength' // 核心力量
  | 'flexibility' // 柔韧灵活
  | 'rehab' // 康复保健
  | 'stress_relief'; // 释压放松

export type TrainingPlan = {
  id: string;
  createdAt: string; // ISO
  startDate: string; // ISO (当天或下周一)
  mode: PlanMode;
  daysOfWeek: number[]; // 0(日) - 6(六)
  sessionsPerWeek: number; // 1..7
  goal: PlanGoal | '';
  startWeightKg?: number;
  preferredTimeOfDay?: 'morning' | 'noon' | 'evening' | '';
  name?: string;
  isActive?: boolean;
};
export interface TrainingPlanListResponse {
  list: TrainingPlan[];
  total: number;
  page: number;
  limit: number;
}

class TrainingPlanApi {
  async create(dto: CreateTrainingPlanDto): Promise<TrainingPlan> {
    return api.post<TrainingPlan>('/training-plans', dto);
  }

  async list(page: number = 1, limit: number = 10): Promise<TrainingPlanListResponse> {
    return api.get<TrainingPlanListResponse>(`/training-plans?page=${page}&limit=${limit}`);
  }

  async detail(id: string): Promise<TrainingPlan> {
    return api.get<TrainingPlan>(`/training-plans/${id}`);
  }

  async update(id: string, dto: CreateTrainingPlanDto): Promise<TrainingPlan> {
    return api.post<TrainingPlan>(`/training-plans/${id}/update`, dto);
  }

  async delete(id: string): Promise<{ success: boolean }> {
    return api.delete<{ success: boolean }>(`/training-plans/${id}`);
  }

  async activate(id: string): Promise<{ success: boolean }> {
    return api.post<{ success: boolean }>(`/training-plans/${id}/activate`);
  }

  async getActivePlan(): Promise<TrainingPlan | null> {
    try {
      return api.get<TrainingPlan>('/training-plans/active');
    } catch (error) {
      // 如果没有激活的计划，返回null
      return null;
    }
  }
}

export const trainingPlanApi = new TrainingPlanApi();