import {
  Body,
  Controller,
  Post,
  UploadedFile,
  UseGuards,
  UseInterceptors,
  BadRequestException,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { ApiKeyGuard } from "../auth/api-key.guard";
import { TxtImportService } from "./txt-import.service";

@UseGuards(ApiKeyGuard)
@Controller("imports")
export class ImportsController {
  constructor(private readonly txtImport: TxtImportService) {}

  @Post("txt")
  @UseInterceptors(FileInterceptor("file"))
  async uploadTxt(
    @UploadedFile() file: Express.Multer.File | undefined,
    @Body()
    body: {
      usuarioId?: string;
      chatRemote?: string;
      ownerNames?: string;
      content?: string;
    },
  ) {
    const usuarioId = body.usuarioId;
    if (!usuarioId) throw new BadRequestException("usuarioId required");
    const content =
      file?.buffer?.toString("utf8") ||
      body.content ||
      "";
    if (!content.trim()) {
      throw new BadRequestException("file or content required");
    }
    const ownerNames = body.ownerNames
      ? body.ownerNames.split(",").map((s) => s.trim()).filter(Boolean)
      : [];
    return this.txtImport.importTxt({
      usuarioId,
      filename: file?.originalname,
      content,
      chatRemote: body.chatRemote,
      ownerNames,
    });
  }
}
