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

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

export async function getDailyQuotes(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 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 rows = await prisma.$queryRaw<Array<{
    date: string;
    buy: number;
    sell: number;
  }>>`
    SELECT DATE("timeStamp")::text AS date, buy::numeric::float8 AS buy, sell::numeric::float8 AS sell FROM (
      SELECT DISTINCT ON (DATE("timeStamp")) "timeStamp", buy, sell
      FROM "quotes_history"
      WHERE "type" = ${rawType}::"QuoteType"
        AND "timeStamp" >= ${startDate}::timestamptz
        AND "timeStamp" < ${endDate}::timestamptz
      ORDER BY DATE("timeStamp"), "timeStamp" DESC
    ) sub
    ORDER BY DATE("timeStamp") ASC
  `;

  return c.json(rows);
}
