import type { Context } from "hono";
import type { QuoteType } from "../../../generated/prisma/client";
import { cache } from "../../../lib/cache";
import { prisma } from "../../../lib/prisma";
import { parseLocalDate, startOfNextLocalDay } from "../../../lib/utils";

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
    ? parseLocalDate(startDateParam)
    : new Date(now.getFullYear(), now.getMonth(), 1);
  const endDate = endDateParam ? startOfNextLocalDay(endDateParam) : now;

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

  const cacheKey = `quotes:history:${type}:${startDate.toISOString()}:${endDate.toISOString()}`;
  const cached = cache.get(cacheKey);
  if (cached) return c.json(cached);

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

  cache.set(cacheKey, history);
  return c.json(history);
}
