import { Controller, Get, Post, Patch, Param, Body, Query, Res, NotFoundException } from '@nestjs/common'
import { Response } from 'express'
import { promises as fs } from 'fs'
import * as path from 'path'
import { DocumentsService } from './documents.service'
import { CreateDocumentDto } from './dto/create-document.dto'
import { UpdateDocumentDto } from './dto/update-document.dto'

@Controller('documents')
export class DocumentsController {
  constructor(private readonly service: DocumentsService) {}

  @Post()
  create(@Body() dto: CreateDocumentDto) {
    return this.service.create(dto)
  }

  @Get()
  findAll(
    @Query('clientFolderId') clientFolderId?: string,
    @Query('matterId') matterId?: string,
    @Query('privilege') privilege?: string,
    @Query('documentType') documentType?: string,
    @Query('limit') limit?: string,
    @Query('offset') offset?: string,
  ) {
    return this.service.findAll({
      clientFolderId, matterId, privilege, documentType,
      limit: limit ? parseInt(limit) : undefined,
      offset: offset ? parseInt(offset) : undefined,
    })
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.service.findOne(id)
  }

  @Patch(':id')
  update(@Param('id') id: string, @Body() dto: UpdateDocumentDto) {
    return this.service.update(id, dto)
  }

  @Post(':id/translate')
  translate(@Param('id') id: string) {
    return this.service.translate(id)
  }

  @Post(':id/save-translation')
  saveTranslation(
    @Param('id') id: string,
    @Body() body: { translatedText: string; targetLang: string },
  ) {
    return this.service.saveTranslation(id, body.translatedText, body.targetLang)
  }

  // Returns raw file bytes — used by the client-manager agent when content was not passed inline
  @Get(':id/content')
  async content(@Param('id') id: string, @Res() res: Response) {
    const doc = await this.service.findOne(id)
    const uploadsRoot = process.env.UPLOADS_DIR ?? path.join(process.cwd(), 'uploads')
    const filePath = path.join(uploadsRoot, doc.storageKey)
    try {
      const buffer = await fs.readFile(filePath)
      res.set('Content-Type', doc.mimeType ?? 'application/octet-stream')
      res.set('Content-Disposition', `inline; filename="${doc.fileName}"`)
      res.send(buffer)
    } catch {
      throw new NotFoundException(`File not found on disk for document ${id}`)
    }
  }
}
