import type { Context } from "hono";
import { prisma } from "../../../lib/prisma";
import { cache } from "../../../lib/cache";

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

export async function getHistoricalMinMax(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 cacheKey = `quotes:historical:minmax:${rawType}`;
  const cached = cache.get(cacheKey);
  if (cached) return c.json(cached);

  const type = rawType as string;

  const rows = await prisma.$queryRaw<Array<{
    minBuy: number;
    maxBuy: number;
    minBuyDate: string;
    maxBuyDate: string;
  }>>`
    SELECT
      (SELECT MIN(buy::numeric)::float8 FROM "quotes_history" WHERE "type" = ${type}::"QuoteType") AS "minBuy",
      (SELECT MAX(buy::numeric)::float8 FROM "quotes_history" WHERE "type" = ${type}::"QuoteType") AS "maxBuy",
      (SELECT "timeStamp"::text FROM "quotes_history" WHERE "type" = ${type}::"QuoteType" ORDER BY buy::numeric ASC LIMIT 1) AS "minBuyDate",
      (SELECT "timeStamp"::text FROM "quotes_history" WHERE "type" = ${type}::"QuoteType" ORDER BY buy::numeric DESC LIMIT 1) AS "maxBuyDate"
  `;

  const result = rows[0] ?? { minBuy: 0, maxBuy: 0, minBuyDate: null, maxBuyDate: null };

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