import type { Context } from "hono";
import { prisma } from "../../../lib/prisma";
import type { QuoteType } from "../../../generated/prisma/client";

const VALID_TYPES = ["BLUE", "BNA", "BELO"] as const;

export async function getQuoteHistory(c: Context) {
  const rawType = c.req.param("type")!.toUpperCase();

  if (!VALID_TYPES.includes(rawType as typeof VALID_TYPES[number])) {
    return c.json({ error: `Invalid quote type. Must be one of: ${VALID_TYPES.join(", ")}` }, 400);
  }

  const type = rawType as QuoteType;
  const startDateParam = c.req.query("startDate");
  const endDateParam = c.req.query("endDate");

  const now = new Date();
  const startDate = startDateParam
    ? new Date(startDateParam)
    : new Date(now.getFullYear(), now.getMonth(), 1);
  const endDate = endDateParam
    ? new Date(new Date(endDateParam).getTime() + 86_400_000)
    : now;

  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    return c.json({ error: "Invalid date format. Use ISO 8601." }, 400);
  }

  const history = await prisma.quoteHistory.findMany({
    where: {
      type,
      timeStamp: { gte: startDate, lt: endDate },
    },
    orderBy: { timeStamp: "asc" },
  });

  return c.json(history);
}
