import { createRoute } from "../../../../../modules/api-utils/createRoute";
import { generatedQuotes } from "../../../../../managers/generatedQuotes";
import { opportunities } from "../../../../../managers/opportunities";
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/quotes/downloads */
export default createRoute(
  "get",
  ["/opportunities/opportunity/:identifier/quotes/downloads"],
  async (c) => {
    const identifier = c.req.param("identifier");

    const opportunity = await opportunities.fetchRecord(identifier);
    const quotes = await generatedQuotes.fetchByOpportunity(opportunity.id);

    const data = quotes.map((quote) => ({
      quoteId: quote.id,
      quoteFileName: quote.quoteFileName,
      createdById: quote.createdById,
      createdAt: quote.createdAt,
      downloads: quote.downloads,
    }));

    const response = apiResponse.successful(
      "Quote download history fetched successfully!",
      data,
    );
    return c.json(response, response.status as ContentfulStatusCode);
  },
  authMiddleware({ permissions: ["sales.opportunity.quote.fetch_downloads"] }),
);
