import {
  Controller,
  Post,
  Delete,
  UseInterceptors,
  UploadedFile,
  Body,
  BadRequestException,
  Logger,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { FileUploadService } from './file-upload.service';

@Controller('files')
export class FileUploadController {
  private readonly logger = new Logger(FileUploadController.name);

  constructor(private readonly fileUploadService: FileUploadService) {}

  /**
   * 上传单个文件
   * POST /api/v1/files/upload
   */
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: memoryStorage(),
      limits: {
        fileSize: 300 * 1024 * 1024, // 300MB
      },
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Body() body: { type?: string; courseId?: string },
  ) {
    this.logger.log(`Uploading file: ${file.originalname}, type: ${body.type || 'unknown'}`);

    if (!file) {
      throw new BadRequestException('没有上传文件');
    }

    // 验证文件类型
    const fileType = body.type || 'other';
    const validationResult = this.fileUploadService.validateFile(file, fileType);

    if (!validationResult.valid) {
      throw new BadRequestException(validationResult.error);
    }

    // 保存文件
    const savedFile = await this.fileUploadService.saveFile(file, fileType, body.courseId);

    this.logger.log(`File uploaded successfully: ${savedFile.filePath}`);

    return {
      success: true,
      filePath: savedFile.filePath,
      fileName: savedFile.fileName,
      originalName: file.originalname,
      fileSize: file.size,
      mimeType: file.mimetype,
    };
  }

  /**
   * 删除文件
   * DELETE /api/v1/files/delete
   */
  @Delete('delete')
  async deleteFile(@Body() body: { filePath: string }) {
    this.logger.log(`Deleting file: ${body.filePath}`);

    if (!body.filePath) {
      throw new BadRequestException('缺少文件路径');
    }

    const result = await this.fileUploadService.deleteFile(body.filePath);

    if (!result.success) {
      throw new BadRequestException(result.error);
    }

    this.logger.log(`File deleted successfully: ${body.filePath}`);

    return {
      success: true,
      message: '文件删除成功',
    };
  }
}
