import { createRoute } from "../../../../../modules/api-utils/createRoute";
import { opportunities } from "../../../../../managers/opportunities";
import { generatedQuotes } from "../../../../../managers/generatedQuotes";
import { apiResponse } from "../../../../../modules/api-utils/apiResponse";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { authMiddleware } from "../../../../middleware/authorization";

/* GET /v1/sales/opportunities/opportunity/:identifier/quote/:quoteId/preview */
export default createRoute(
  "get",
  ["/opportunities/opportunity/:identifier/quote/:quoteId/preview"],
  async (c) => {
    const identifier = c.req.param("identifier");
    const quoteId = c.req.param("quoteId");

    const item = await opportunities.fetchRecord(identifier);
    const quote = await generatedQuotes.fetch(quoteId);

    const regenData =
      quote.quoteRegenData && typeof quote.quoteRegenData === "object"
        ? (quote.quoteRegenData as Record<string, unknown>)
        : {};

    const options =
      regenData.options && typeof regenData.options === "object"
        ? (regenData.options as Record<string, unknown>)
        : {};

    const creator = await quote.fetchCreatedBy();

    const previewBuffer = await item.generateQuote({
      lineItemPricing: options.lineItemPricing as boolean | undefined,
      includeQuoteNarrative: options.includeQuoteNarrative as
        | boolean
        | undefined,
      includeItemNarratives: options.includeItemNarratives as
        | boolean
        | undefined,
      showPreview: true,
      metadata: {
        quoteId: quote.id,
        createdById: quote.createdById ?? undefined,
        createdByName: creator?.name ?? undefined,
        createdByEmail: creator?.email ?? undefined,
        createdAt: quote.createdAt?.toISOString(),
      },
    });

    const previewBase64 = Buffer.from(previewBuffer).toString("base64");

    const response = apiResponse.successful(
      "Quote preview generated successfully!",
      {
        mimeType: "application/pdf",
        contentBase64: previewBase64,
      }
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.quote.preview"] })
);
