import {
  Controller,
  Post,
  UploadedFile,
  UseGuards,
  UseInterceptors,
  BadRequestException,
  InternalServerErrorException,
} from "@nestjs/common";
import { FileInterceptor } from "@nestjs/platform-express";
import { JwtAuthGuard } from "./jwt-auth.guard";
import * as FormData from "form-data";
import fetch from "node-fetch";
import type { RequestInit } from "node-fetch";

const EXTRACTION_SERVICE_URL =
  process.env.EXTRACTION_SERVICE_URL ?? "http://localhost:8096";

@Controller("extract")
@UseGuards(JwtAuthGuard)
export class ExtractionController {
  /**
   * POST /api/extract/invoice
   * Accepts a multipart file upload, forwards it to the Python extraction
   * service at POST /extract/invoice, and returns the extracted JSON.
   */
  @Post("invoice")
  @UseInterceptors(FileInterceptor("file"))
  async extractInvoice(@UploadedFile() file: Express.Multer.File & { buffer: Buffer; originalname: string; mimetype: string }) {
    if (!file) throw new BadRequestException("No file uploaded");

    const form = new FormData();
    form.append("file", file.buffer, {
      filename: file.originalname,
      contentType: file.mimetype,
    });

    let res: Awaited<ReturnType<typeof fetch>>;
    try {
      res = await fetch(`${EXTRACTION_SERVICE_URL}/extract/invoice`, {
        method: "POST",
        body: form as unknown as RequestInit["body"],
        headers: form.getHeaders() as Record<string, string>,
      });
    } catch (err) {
      throw new InternalServerErrorException(
        `Extraction service unreachable: ${(err as Error).message}`,
      );
    }

    if (!res.ok) {
      const body = await res.text();
      throw new InternalServerErrorException(
        `Extraction service error (${res.status}): ${body}`,
      );
    }

    return res.json();
  }
}
