import { BadRequestException, Body, Controller, Post, Req, UploadedFile, UseGuards, UseInterceptors } from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { Request } from "express";
import { JwtAuthGuard } from "./jwt-auth.guard";
import { JwtPayload } from "./auth.service";
import { ImportPreviewResult, ImportService } from "./import.service";

interface AuthedRequest extends Request {
  user?: JwtPayload;
}

@Controller("import")
@UseGuards(JwtAuthGuard)
export class ImportController {
  constructor(private readonly importService: ImportService) {}

  @Post("preview")
  @UseInterceptors(FileInterceptor("file"))
  async preview(@UploadedFile() file: Express.Multer.File & { buffer: Buffer; originalname: string }) {
    if (!file) throw new BadRequestException("No file uploaded");
    return this.importService.preview(file.buffer, file.originalname);
  }

  @Post("commit")
  async commit(@Body() body: ImportPreviewResult, @Req() req: AuthedRequest) {
    const actorName = req.user?.name ?? req.user?.email ?? "Unknown";
    return this.importService.commit(body, { name: actorName });
  }
}
