import { Injectable, Logger } from '@nestjs/common';

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;
}

export interface CourseValidationData {
  name?: string;
  description?: string;
  coverImagePath?: string;
  gradeTags?: string;
  domainTags?: string;
  duration?: number;
  ebookPaths?: string;
  audioPaths?: string;
  videoPaths?: string;
  otherResources?: string;
  scripts?: any[];
  lessonPlanData?: string;  // JSON字符串，包含 phases 和 scriptPages
}

/**
 * 课程发布前验证服务
 * 验证课程内容的完整性和合规性
 */
@Injectable()
export class CourseValidationService {
  private readonly logger = new Logger(CourseValidationService.name);

  /**
   * 验证课程是否可以提交审核
   */
  async validateForSubmit(course: CourseValidationData): Promise<ValidationResult> {
    const errors: ValidationError[] = [];
    const warnings: ValidationWarning[] = [];

    // 1. 验证基本信息
    this.validateBasicInfo(course, errors);

    // 2. 验证封面图片
    this.validateCover(course, errors);

    // 3. 验证年级标签
    this.validateGradeTags(course, errors);

    // 4. 验证课程时长
    this.validateDuration(course, errors);

    // 5. 验证数字资源
    this.validateResources(course, warnings);

    // 6. 验证教学流程
    this.validateScripts(course, errors);

    const result: ValidationResult = {
      valid: errors.length === 0,
      errors,
      warnings,
    };

    this.logger.log(`Validation result: valid=${result.valid}, errors=${errors.length}, warnings=${warnings.length}`);

    return result;
  }

  /**
   * 验证基本信息
   */
  private validateBasicInfo(course: CourseValidationData, errors: ValidationError[]): void {
    // 课程名称
    if (!course.name || course.name.trim().length === 0) {
      errors.push({
        field: 'name',
        message: '请输入课程名称',
        code: 'NAME_REQUIRED',
      });
    } else if (course.name.length < 2) {
      errors.push({
        field: 'name',
        message: '课程名称至少需要2个字符',
        code: 'NAME_TOO_SHORT',
      });
    } else if (course.name.length > 50) {
      errors.push({
        field: 'name',
        message: '课程名称不能超过50个字符',
        code: 'NAME_TOO_LONG',
      });
    }
  }

  /**
   * 验证封面图片
   */
  private validateCover(course: CourseValidationData, errors: ValidationError[]): void {
    if (!course.coverImagePath) {
      errors.push({
        field: 'coverImagePath',
        message: '请上传课程封面',
        code: 'COVER_REQUIRED',
      });
    }
  }

  /**
   * 验证年级标签
   */
  private validateGradeTags(course: CourseValidationData, errors: ValidationError[]): void {
    if (!course.gradeTags) {
      errors.push({
        field: 'gradeTags',
        message: '请选择适用年级',
        code: 'GRADE_REQUIRED',
      });
      return;
    }

    try {
      const grades = JSON.parse(course.gradeTags);
      if (!Array.isArray(grades) || grades.length === 0) {
        errors.push({
          field: 'gradeTags',
          message: '请至少选择一个适用年级',
          code: 'GRADE_EMPTY',
        });
      }
    } catch {
      errors.push({
        field: 'gradeTags',
        message: '年级标签格式错误',
        code: 'GRADE_FORMAT_ERROR',
      });
    }
  }

  /**
   * 验证课程时长
   */
  private validateDuration(course: CourseValidationData, errors: ValidationError[]): void {
    if (course.duration === undefined || course.duration === null) {
      errors.push({
        field: 'duration',
        message: '请设置课程时长',
        code: 'DURATION_REQUIRED',
      });
      return;
    }

    if (course.duration < 5) {
      errors.push({
        field: 'duration',
        message: '课程时长不能少于5分钟',
        code: 'DURATION_TOO_SHORT',
      });
    } else if (course.duration > 60) {
      errors.push({
        field: 'duration',
        message: '课程时长不能超过60分钟',
        code: 'DURATION_TOO_LONG',
      });
    }
  }

  /**
   * 验证数字资源
   */
  private validateResources(course: CourseValidationData, warnings: ValidationWarning[]): void {
    const hasEbook = this.hasValidJsonArray(course.ebookPaths);
    const hasAudio = this.hasValidJsonArray(course.audioPaths);
    const hasVideo = this.hasValidJsonArray(course.videoPaths);
    const hasOther = this.hasValidJsonArray(course.otherResources);

    if (!hasEbook && !hasAudio && !hasVideo && !hasOther) {
      warnings.push({
        field: 'resources',
        message: '建议上传至少1个数字资源（电子绘本、音频或视频）',
        code: 'RESOURCES_SUGGESTED',
      });
    }
  }

  /**
   * 验证教学流程
   */
  private validateScripts(course: CourseValidationData, errors: ValidationError[]): void {
    // 优先检查 lessonPlanData 中的 phases（新数据结构）
    if (course.lessonPlanData) {
      try {
        const lessonPlan = JSON.parse(course.lessonPlanData);
        if (!lessonPlan.phases || !Array.isArray(lessonPlan.phases) || lessonPlan.phases.length === 0) {
          errors.push({
            field: 'lessonPlanData',
            message: '请至少配置一个教学环节',
            code: 'SCRIPTS_REQUIRED',
          });
        }
        return;  // 使用新数据结构验证完成
      } catch {
        errors.push({
          field: 'lessonPlanData',
          message: '教学计划数据格式错误',
          code: 'LESSON_PLAN_FORMAT_ERROR',
        });
        return;
      }
    }

    // 兼容旧的 scripts 字段
    if (course.scripts !== undefined) {
      if (!Array.isArray(course.scripts) || course.scripts.length === 0) {
        errors.push({
          field: 'scripts',
          message: '请至少配置一个教学环节',
          code: 'SCRIPTS_REQUIRED',
        });
      }
    }
  }

  /**
   * 检查是否是有效的JSON数组
   */
  private hasValidJsonArray(jsonStr: string | undefined | null): boolean {
    if (!jsonStr) return false;

    try {
      const arr = JSON.parse(jsonStr);
      return Array.isArray(arr) && arr.length > 0;
    } catch {
      return false;
    }
  }

  /**
   * 快速检查课程是否可以提交（只返回布尔值）
   */
  async canSubmit(course: CourseValidationData): Promise<boolean> {
    const result = await this.validateForSubmit(course);
    return result.valid;
  }

  /**
   * 获取验证摘要（用于显示）
   */
  getValidationSummary(result: ValidationResult): string {
    if (result.valid && result.warnings.length === 0) {
      return '课程内容完整，可以提交审核';
    }

    if (result.valid && result.warnings.length > 0) {
      return `课程可以提交，但有 ${result.warnings.length} 条建议`;
    }

    return `课程有 ${result.errors.length} 个问题需要修复`;
  }
}
