import { api } from './api';

// 训练项目数据结构
export interface ScheduleExercise {
  id: string;
  trainingPlanId: string;
  userId: string;
  exerciseKey?: string;
  name: string;
  sets?: number;
  reps?: number;
  durationSec?: number;
  restSec?: number;
  note?: string;
  itemType: 'exercise' | 'rest' | 'note';
  completed: boolean;
  sortOrder: number;
  createdAt: string;
  updatedAt: string;
  deleted: boolean;

  // 关联的动作信息（仅exercise类型时存在）
  exercise?: {
    key: string;
    name: string;
    description: string;
    categoryKey: string;
    categoryName: string;
  };
}

// 创建训练项目的请求体
export interface CreateScheduleExerciseDto {
  exerciseKey?: string;
  name: string;
  sets?: number;
  reps?: number;
  durationSec?: number;
  restSec?: number;
  note?: string;
  itemType: 'exercise' | 'rest' | 'note';
}

// 更新训练项目的请求体
export interface UpdateScheduleExerciseDto {
  exerciseKey?: string;
  name?: string;
  sets?: number;
  reps?: number;
  durationSec?: number;
  restSec?: number;
  note?: string;
  itemType?: 'exercise' | 'rest' | 'note';
  completed?: boolean;
}

// 完成状态统计
export interface CompletionStats {
  total: number;
  completed: number;
  percentage: number;
}

// 重新排序请求体
export interface ReorderExercisesDto {
  exerciseIds: string[];
}

class ScheduleExerciseApi {
  // 获取训练计划的所有项目
  async list(planId: string): Promise<ScheduleExercise[]> {
    return api.get<ScheduleExercise[]>(`/training-plans/${planId}/exercises`);
  }

  // 获取训练项目详情
  async detail(planId: string, exerciseId: string): Promise<ScheduleExercise> {
    return api.get<ScheduleExercise>(`/training-plans/${planId}/exercises/${exerciseId}`);
  }

  // 添加训练项目
  async create(planId: string, dto: CreateScheduleExerciseDto): Promise<ScheduleExercise> {
    return api.post<ScheduleExercise>(`/training-plans/${planId}/exercises`, dto);
  }

  // 更新训练项目
  async update(planId: string, exerciseId: string, dto: UpdateScheduleExerciseDto): Promise<ScheduleExercise> {
    return api.put<ScheduleExercise>(`/training-plans/${planId}/exercises/${exerciseId}`, dto);
  }

  // 删除训练项目
  async delete(planId: string, exerciseId: string): Promise<{ success: boolean }> {
    return api.delete<{ success: boolean }>(`/training-plans/${planId}/exercises/${exerciseId}`);
  }

  // 更新训练项目排序
  async reorder(planId: string, dto: ReorderExercisesDto): Promise<{ success: boolean }> {
    return api.put<{ success: boolean }>(`/training-plans/${planId}/exercises/order`, dto);
  }

  // 标记训练项目完成状态
  async updateCompletion(planId: string, exerciseId: string, completed: boolean): Promise<ScheduleExercise> {
    return api.put<ScheduleExercise>(`/training-plans/${planId}/exercises/${exerciseId}/complete`, { completed });
  }
}

export const scheduleExerciseApi = new ScheduleExerciseApi();
