import { Controller, Post, UseInterceptors, UploadedFile, HttpException, HttpStatus } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import * as mammoth from 'mammoth'
import { memoryStorage } from 'multer'

// eslint-disable-next-line @typescript-eslint/no-var-requires
const pdfParse = require('pdf-parse')

@Controller('upload')
export class UploadController {
  @Post()
  @UseInterceptors(FileInterceptor('file', {
    storage: memoryStorage(),
    limits: { fileSize: 10 * 1024 * 1024 },
  }))
  async uploadFile(@UploadedFile() file: any) {
    if (!file) {
      throw new HttpException('请选择文件', HttpStatus.BAD_REQUEST)
    }

    const ext = file.originalname.toLowerCase().split('.').pop() || ''
    let text = ''

    try {
      switch (ext) {
        case 'pdf':
          const pdfData = await pdfParse(file.buffer)
          text = pdfData.text
          break
        case 'docx':
          const docxResult = await mammoth.extractRawText({ buffer: file.buffer })
          text = docxResult.value
          break
        case 'doc':
          text = '[旧版 Word 格式 (.doc) 暂不支持解析，请转换为 .docx 或粘贴文本]'
          break
        case 'txt':
          text = file.buffer.toString('utf-8')
          break
        default:
          throw new HttpException('不支持的文件格式，请上传 PDF、DOCX 或 TXT', HttpStatus.BAD_REQUEST)
      }
    } catch (e: any) {
      if (e instanceof HttpException) throw e
      throw new HttpException('文件解析失败：' + (e.message || '未知错误'), HttpStatus.INTERNAL_SERVER_ERROR)
    }

    if (!text.trim()) {
      throw new HttpException('未能从文件中提取到有效文本', HttpStatus.BAD_REQUEST)
    }

    return {
      text: text.trim(),
      fileName: file.originalname,
      fileSize: file.size,
    }
  }
}
