import { readingApi } from "./client";
import type {
  GetCoursePage1Params,
  ResultPageResultCourse,
  Course as ApiCourse,
  ApproveCourseParams,
  RejectCourseParams,
} from "./generated/model";

export type CourseQueryParams = GetCoursePage1Params;

export type Course = ApiCourse;

export interface CourseLesson {
  id: number;
  courseId: number;
  lessonType: string;
  name: string;
  description?: string;
  duration: number;
  videoPath?: string;
  videoName?: string;
  pptPath?: string;
  pptName?: string;
  pdfPath?: string;
  pdfName?: string;
  objectives?: string;
  preparation?: string;
  extension?: string;
  reflection?: string;
  assessmentData?: string;
  useTemplate: boolean;
  sortOrder: number;
  steps?: LessonStep[];
}

export interface LessonStep {
  id: number;
  lessonId: number;
  name: string;
  content?: string;
  duration: number;
  objective?: string;
  resourceIds?: string;
  sortOrder: number;
}

export interface ValidationResult {
  valid: boolean;
  errors: ValidationError[];
  warnings: ValidationWarning[];
}

export interface ValidationError {
  field: string;
  message: string;
  code: string;
}

export interface ValidationWarning {
  field: string;
  message: string;
  code: string;
}

// 获取课程包列表（使用 Orval 生成的分页接口，并适配为原有扁平结构）
export function getCourses(params: CourseQueryParams): Promise<{
  items: Course[];
  total: number;
  page: number;
  pageSize: number;
}> {
  return readingApi.getCoursePage1(params).then((res) => {
    const wrapped = res as ResultPageResultCourse;
    const pageData = wrapped.data;

    return {
      items: (pageData?.items as Course[]) ?? [],
      total: pageData?.total ?? 0,
      page: pageData?.page ?? params.page ?? 1,
      pageSize: pageData?.pageSize ?? params.pageSize ?? 10,
    };
  });
}

// 获取审核列表
export function getReviewList(params: CourseQueryParams): Promise<{
  items: Course[];
  total: number;
  page: number;
  pageSize: number;
}> {
  // 审核列表对应 Orval 的 getReviewCoursePage，返回结构同课程分页
  return readingApi.getReviewCoursePage(params as any).then((res) => {
    const wrapped = res as ResultPageResultCourse;
    const pageData = wrapped.data;

    return {
      items: (pageData?.items as Course[]) ?? [],
      total: pageData?.total ?? 0,
      page: pageData?.page ?? params.page ?? 1,
      pageSize: pageData?.pageSize ?? params.pageSize ?? 10,
    };
  });
}

// 获取课程包详情
export function getCourse(id: number): Promise<unknown> {
  return readingApi.getCourse3(id).then((res) => res);
}

// 创建课程包
export function createCourse(data: unknown): Promise<unknown> {
  return readingApi.createCourse1(data as any).then((res) => res);
}

// 更新课程包
export function updateCourse(id: number, data: unknown): Promise<unknown> {
  return readingApi.updateCourse1(id, data as any).then((res) => res);
}

// 删除课程包
export function deleteCourse(id: number): Promise<unknown> {
  return readingApi.deleteCourse1(id).then((res) => res);
}

// 验证课程完整性
export function validateCourse(id: number): Promise<ValidationResult> {
  // 暂无对应 Orval 接口，继续使用旧路径
  const { http } = require("./index");
  return http.get(`/api/v1/admin/courses/${id}/validate`);
}

// 提交审核
export function submitCourse(
  id: number,
  _copyrightConfirmed: boolean,
): Promise<unknown> {
  // 后端接口签名只需要 ID，版权确认逻辑在前端自行控制
  return readingApi.submitCourse(id).then((res) => res);
}

// 撤销审核
export function withdrawCourse(id: number): Promise<unknown> {
  return readingApi.withdrawCourse(id).then((res) => res);
}

// 审核通过
export function approveCourse(
  id: number,
  data: { checklist?: any; comment?: string },
): Promise<unknown> {
  const params: ApproveCourseParams = {
    comment: data.comment,
  };
  return readingApi.approveCourse(id, params).then((res) => res);
}

// 审核驳回
export function rejectCourse(
  id: number,
  data: { checklist?: any; comment: string },
): Promise<unknown> {
  const params: RejectCourseParams = {
    comment: data.comment,
  };
  return readingApi.rejectCourse(id, params).then((res) => res);
}

// 直接发布（超级管理员）
export function directPublishCourse(
  id: number,
  _skipValidation?: boolean,
): Promise<unknown> {
  // skipValidation 由后端接口定义控制，这里总是调用“直接发布”接口
  return readingApi.directPublishCourse(id).then((res) => res);
}

// 发布课程包（兼容旧API）
export function publishCourse(id: number): Promise<unknown> {
  return readingApi.publishCourse(id).then((res) => res);
}

// 下架课程包
export function unpublishCourse(id: number): Promise<unknown> {
  return readingApi.unpublishCourse(id).then((res) => res);
}

// 重新发布
export function republishCourse(id: number): Promise<unknown> {
  return readingApi.republishCourse(id).then((res) => res);
}

// 获取课程包统计数据
export function getCourseStats(id: number): Promise<unknown> {
  // 统计接口在 OpenAPI 中与当前使用的字段含义略有差异，暂时保留旧实现
  const { http } = require("./index");
  return http.get(`/api/v1/admin/courses/${id}/stats`);
}

// 获取版本历史
export function getCourseVersions(id: number): Promise<unknown[]> {
  const { http } = require("./index");
  return http.get(`/api/v1/admin/courses/${id}/versions`);
}

// 课程状态映射
export const COURSE_STATUS_MAP: Record<
  string,
  { label: string; color: string }
> = {
  DRAFT: { label: "草稿", color: "default" },
  PENDING: { label: "审核中", color: "processing" },
  REJECTED: { label: "已驳回", color: "error" },
  PUBLISHED: { label: "已发布", color: "success" },
  ARCHIVED: { label: "已下架", color: "warning" },
};

// 获取状态显示信息
export function getCourseStatusInfo(status: string) {
  return COURSE_STATUS_MAP[status] || { label: status, color: "default" };
}
