import axios from 'axios';

const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api/v1';

export interface UploadResult {
  success: boolean;
  filePath: string;
  fileName: string;
  originalName: string;
  fileSize: number;
  mimeType: string;
}

export interface DeleteResult {
  success: boolean;
  message: string;
}

/**
 * 文件上传 API
 */
export const fileApi = {
  /**
   * 上传文件
   */
  uploadFile: async (
    file: File,
    type: 'cover' | 'ebook' | 'audio' | 'video' | 'ppt' | 'poster' | 'document' | 'other',
    courseId?: number,
  ): Promise<UploadResult> => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', type);
    if (courseId) {
      formData.append('courseId', courseId.toString());
    }

    const response = await axios.post<UploadResult>(
      `${API_BASE}/files/upload`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
        // 添加上传进度回调
        onUploadProgress: (progressEvent) => {
          if (progressEvent.total) {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(`Upload progress: ${percentCompleted}%`);
          }
        },
      },
    );

    return response.data;
  },

  /**
   * 删除文件
   */
  deleteFile: async (filePath: string): Promise<DeleteResult> => {
    const response = await axios.delete<DeleteResult>(`${API_BASE}/files/delete`, {
      data: { filePath },
    });
    return response.data;
  },

  /**
   * 获取文件URL
   */
  getFileUrl: (filePath: string): string => {
    // filePath 格式: /uploads/courses/covers/xxx.png
    // 直接返回相对路径，由 nginx 或后端静态服务处理
    return filePath;
  },
};

/**
 * 文件类型常量
 */
export const FILE_TYPES = {
  COVER: 'cover',
  EBOOK: 'ebook',
  AUDIO: 'audio',
  VIDEO: 'video',
  PPT: 'ppt',
  POSTER: 'poster',
  DOCUMENT: 'document',
  OTHER: 'other',
} as const;

/**
 * 文件大小限制（字节）
 */
export const FILE_SIZE_LIMITS = {
  COVER: 10 * 1024 * 1024,      // 10MB
  EBOOK: 300 * 1024 * 1024,     // 300MB
  AUDIO: 300 * 1024 * 1024,     // 300MB
  VIDEO: 300 * 1024 * 1024,     // 300MB
  PPT: 300 * 1024 * 1024,       // 300MB
  POSTER: 10 * 1024 * 1024,     // 10MB
  DOCUMENT: 300 * 1024 * 1024,  // 300MB
  OTHER: 300 * 1024 * 1024,     // 300MB
} as const;

/**
 * 每个分类最大文件数量
 */
export const MAX_FILE_COUNT = 15;

/**
 * 文件类型验证
 */
export const validateFileType = (
  file: File,
  type: keyof typeof FILE_SIZE_LIMITS,
): { valid: boolean; error?: string } => {
  const maxSize = FILE_SIZE_LIMITS[type];

  if (file.size > maxSize) {
    const maxSizeMB = (maxSize / (1024 * 1024)).toFixed(0);
    return {
      valid: false,
      error: `文件大小超过限制，最大允许 ${maxSizeMB}MB`,
    };
  }

  return { valid: true };
};

// 导出便捷函数
export const uploadFile = fileApi.uploadFile;
export const deleteFile = fileApi.deleteFile;
export const getFileUrl = fileApi.getFileUrl;
