import type { RuntimeMode } from "../shared/api";

import { createApiError, jsonResponse } from "./helpers";

const MAX_PAGE_SIZE = 200;
const MAX_RECENT_LIMIT = 200;

export function validateDashboardWindow(
  windowParam: null | string,
  mode: RuntimeMode,
): Response | { from: string; label: string; to: string } {
  const window = windowParam ?? "24h";
  if (window !== "24h") {
    return jsonResponse(createApiError("Unsupported window parameter", 400), { mode, status: 400 });
  }

  const to = new Date();
  const from = new Date(to.getTime() - 24 * 60 * 60 * 1000);
  return { from: from.toISOString(), label: window, to: to.toISOString() };
}

export function validateMetricsBucket(bucketParam: null | string, mode: RuntimeMode): Response | { bucket: "1h" } {
  const bucket = bucketParam ?? "1h";
  if (bucket !== "1h") {
    return jsonResponse(createApiError("Unsupported bucket parameter", 400), { mode, status: 400 });
  }

  return { bucket };
}

export function validatePagination(
  pageParam: null | string,
  pageSizeParam: null | string,
  mode: RuntimeMode,
): Response | { page: number; pageSize: number } {
  let page = 1;
  let pageSize = 20;

  if (pageParam !== null) {
    page = Number(pageParam);
    if (!Number.isInteger(page) || page <= 0) {
      return jsonResponse(createApiError("Invalid page parameter", 400), { mode, status: 400 });
    }
  }

  if (pageSizeParam !== null) {
    pageSize = Number(pageSizeParam);
    if (!Number.isInteger(pageSize) || pageSize <= 0) {
      return jsonResponse(createApiError("Invalid pageSize parameter", 400), { mode, status: 400 });
    }
    if (pageSize > MAX_PAGE_SIZE) {
      return jsonResponse(createApiError(`pageSize must not exceed ${MAX_PAGE_SIZE}`, 400), { mode, status: 400 });
    }
  }

  return { page, pageSize };
}

export function validateRecentLimit(limitParam: null | string, mode: RuntimeMode): Response | { recentLimit: number } {
  const recentLimit = limitParam === null ? 30 : Number(limitParam);
  if (!Number.isInteger(recentLimit) || recentLimit <= 0) {
    return jsonResponse(createApiError("Invalid recentLimit parameter", 400), { mode, status: 400 });
  }

  if (recentLimit > MAX_RECENT_LIMIT) {
    return jsonResponse(createApiError(`recentLimit must not exceed ${MAX_RECENT_LIMIT}`, 400), { mode, status: 400 });
  }

  return { recentLimit };
}

export function validateTargetId(idStr: string, mode: RuntimeMode): Response | { id: string } {
  if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(idStr)) {
    return jsonResponse(createApiError("Invalid target ID", 400), { mode, status: 400 });
  }
  return { id: idStr };
}

export function validateTimeRange(
  from: null | string,
  to: null | string,
  mode: RuntimeMode,
): Response | { from: string; to: string } {
  if (!from || !to) {
    return jsonResponse(createApiError("from and to parameters are required", 400), { mode, status: 400 });
  }

  const fromDate = new Date(from);
  const toDate = new Date(to);

  if (isNaN(fromDate.getTime()) || isNaN(toDate.getTime())) {
    return jsonResponse(createApiError("Invalid from or to parameter format", 400), { mode, status: 400 });
  }

  if (fromDate.getTime() > toDate.getTime()) {
    return jsonResponse(createApiError("from must be earlier than to", 400), { mode, status: 400 });
  }

  return { from: fromDate.toISOString(), to: toDate.toISOString() };
}
