import { Controller, Get, Post, Patch, Param, Body, Query, UseInterceptors, UploadedFiles, BadRequestException } from '@nestjs/common'
import { FilesInterceptor } from '@nestjs/platform-express'
import { ClientFoldersService } from './client-folders.service'
import { MigrateService } from './migrate.service'
import { CreateClientFolderDto } from './dto/create-client-folder.dto'
import { UpdateClientFolderDto } from './dto/update-client-folder.dto'
import { MigrateImportDto } from './dto/migrate.dto'

@Controller('client-folders')
export class ClientFoldersController {
  constructor(
    private readonly service: ClientFoldersService,
    private readonly migrate: MigrateService,
  ) {}

  @Post('migrate')
  migrateImport(@Body() dto: MigrateImportDto) {
    return this.migrate.import(dto)
  }

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

  @Get()
  findAll(
    @Query('status') status?: string,
    @Query('attorney') attorney?: string,
    @Query('search') search?: string,
    @Query('limit') limit?: string,
    @Query('offset') offset?: string,
  ) {
    return this.service.findAll({
      status, attorney, search,
      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: UpdateClientFolderDto) {
    return this.service.update(id, dto)
  }

  @Post(':id/activate')
  activate(@Param('id') id: string, @Body('engagementLetterRef') ref: string) {
    return this.service.activate(id, ref)
  }

  @Post(':id/close')
  close(@Param('id') id: string, @Body('outcome') outcome: string) {
    return this.service.close(id, outcome)
  }

  @Post(':id/convert')
  convertToClient(@Param('id') id: string, @Body('engagementLetterRef') ref: string) {
    return this.service.convertToClient(id, ref ?? '')
  }

  // Multipart document upload — accepts up to 20 files per request.
  // Files are assigned Bates numbers, persisted, and enqueued for AI classification.
  @Post(':id/documents/upload')
  @UseInterceptors(FilesInterceptor('files', 20))
  uploadDocuments(
    @Param('id') id: string,
    @UploadedFiles() files: Express.Multer.File[],
    @Body('uploadedBy') uploadedBy: string,
  ) {
    if (!files?.length) throw new BadRequestException('No files provided')
    return this.service.uploadDocuments(id, files, uploadedBy ?? 'unknown')
  }
}
