import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  UseGuards,
  Request,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { memoryStorage } from 'multer';
import { UploadService } from './upload.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post()
  @UseGuards(JwtAuthGuard)
  @UseInterceptors(
    FileInterceptor('file', {
      storage: memoryStorage(),
      limits: {
        fileSize: 100 * 1024 * 1024, // 限制文件大小为 100MB
      },
    }),
  )
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Request() req,
  ): Promise<{ url: string; fileName: string; size: number }> {
    if (!file) {
      throw new BadRequestException('请选择要上传的文件');
    }

    const tenantId = req.tenantId || req.user?.tenantId;
    const userId = req.user?.userId;

    const result = await this.uploadService.uploadFile(file, tenantId, userId);

    return {
      url: result.url,
      fileName: result.fileName,
      size: result.size,
    };
  }
}

