import { getSessionUser } from "@/lib/auth";
import { isKavenixAdminEmail } from "@/lib/kavenix-admin";
import {
  getKavenixStatisticsDetail,
  normalizeKavenixStatisticsDate,
  normalizeKavenixStatisticsMetricKey,
} from "@/lib/kavenix-statistics";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

const NO_STORE_HEADERS = {
  "Cache-Control": "no-store, max-age=0",
};

export async function GET(request: Request) {
  const user = await getSessionUser();

  if (!user) {
    return Response.json(
      { error: "unauthorized", message: "로그인이 필요합니다." },
      { status: 401, headers: NO_STORE_HEADERS },
    );
  }

  if (!isKavenixAdminEmail(user.email)) {
    return Response.json(
      { error: "forbidden", message: "최고관리자만 조회할 수 있습니다." },
      { status: 403, headers: NO_STORE_HEADERS },
    );
  }

  const searchParams = new URL(request.url).searchParams;
  const date = normalizeKavenixStatisticsDate(searchParams.get("date"));
  const metricKey = normalizeKavenixStatisticsMetricKey(searchParams.get("metric"));

  if (!date || !metricKey) {
    return Response.json(
      { error: "invalid-query", message: "조회할 날짜와 지표가 올바르지 않습니다." },
      { status: 400, headers: NO_STORE_HEADERS },
    );
  }

  try {
    const detail = await getKavenixStatisticsDetail(date, metricKey);
    return Response.json(
      { detail, ok: true },
      { status: 200, headers: NO_STORE_HEADERS },
    );
  } catch (error) {
    console.error("Unable to load Kavenix statistics detail", error);
    return Response.json(
      { error: "statistics-detail-load-failed", message: "상세 통계를 불러오지 못했습니다." },
      { status: 500, headers: NO_STORE_HEADERS },
    );
  }
}
