import {
  Controller,
  Post,
  Get,
  Delete,
  Param,
  Body,
  Query,
  UploadedFile,
  UseInterceptors,
  Headers,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileService } from '../../application/services/file.service';
import {
  UploadFileDto,
  PresignedUrlDto,
  FileResponseDto,
  PresignedUrlResponseDto,
} from '../../application/dtos/upload-file.dto';

@Controller('files')
export class FileController {
  constructor(private readonly fileService: FileService) {}

  /**
   * 获取预签名上传 URL (用于大文件直传)
   */
  @Post('presigned-url')
  async getPresignedUrl(
    @Headers('x-user-id') userId: string,
    @Body() dto: PresignedUrlDto,
  ): Promise<PresignedUrlResponseDto> {
    return this.fileService.getPresignedUploadUrl(userId, dto);
  }

  /**
   * 确认上传完成
   */
  @Post(':id/confirm')
  async confirmUpload(
    @Headers('x-user-id') userId: string,
    @Param('id', ParseUUIDPipe) fileId: string,
    @Body('size') size: number,
  ): Promise<FileResponseDto> {
    return this.fileService.confirmUpload(userId, fileId, size);
  }

  /**
   * 直接上传文件 (适用于小文件 < 10MB)
   */
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      limits: { fileSize: 10 * 1024 * 1024 }, // 10MB limit for direct upload
    }),
  )
  async uploadFile(
    @Headers('x-user-id') userId: string,
    @UploadedFile() file: Express.Multer.File,
    @Body() dto: UploadFileDto,
  ): Promise<FileResponseDto> {
    return this.fileService.uploadFile(userId, file, dto.conversationId);
  }

  /**
   * 获取文件信息
   */
  @Get(':id')
  async getFile(
    @Headers('x-user-id') userId: string,
    @Param('id', ParseUUIDPipe) fileId: string,
  ): Promise<FileResponseDto> {
    return this.fileService.getFile(userId, fileId);
  }

  /**
   * 获取文件下载 URL
   */
  @Get(':id/download-url')
  async getDownloadUrl(
    @Headers('x-user-id') userId: string,
    @Param('id', ParseUUIDPipe) fileId: string,
  ): Promise<{ url: string }> {
    const url = await this.fileService.getDownloadUrl(userId, fileId);
    return { url };
  }

  /**
   * 获取用户的所有文件
   */
  @Get()
  async getUserFiles(
    @Headers('x-user-id') userId: string,
    @Query('conversationId') conversationId?: string,
  ): Promise<FileResponseDto[]> {
    return this.fileService.getUserFiles(userId, conversationId);
  }

  /**
   * 删除文件
   */
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async deleteFile(
    @Headers('x-user-id') userId: string,
    @Param('id', ParseUUIDPipe) fileId: string,
  ): Promise<void> {
    return this.fileService.deleteFile(userId, fileId);
  }
}
