import { BadRequestException } from '@nestjs/common';
import { DashboardMetric } from '../../generated/prisma/enums';

export const DEFAULT_DASHBOARD_METRICS: DashboardMetric[] = [
  DashboardMetric.primary_metric,
  DashboardMetric.website_traffic,
  DashboardMetric.keyword_rankings,
  DashboardMetric.backlinks,
];

export const REPORT_METRIC_FIELDS = {
  [DashboardMetric.primary_metric]: ['businessMetricValue'],
  [DashboardMetric.website_traffic]: ['traffic'],
  [DashboardMetric.backlinks]: ['backlinks', 'newBacklinks'],
  [DashboardMetric.application_downloads]: ['applicationDownloads'],
} as const;

type ReportMetricInput = Partial<
  Record<
    (typeof REPORT_METRIC_FIELDS)[keyof typeof REPORT_METRIC_FIELDS][number],
    number
  >
>;

export function assertSelectedReportMetrics(
  dashboardMetrics: DashboardMetric[],
  input: ReportMetricInput,
  requireSelectedMetrics = false,
) {
  const selected = new Set(dashboardMetrics);
  for (const [metric, fields] of Object.entries(REPORT_METRIC_FIELDS) as Array<
    [DashboardMetric, readonly string[]]
  >) {
    for (const field of fields) {
      const value = input[field as keyof ReportMetricInput];
      if (
        requireSelectedMetrics &&
        selected.has(metric) &&
        value === undefined
      ) {
        throw new BadRequestException(`${field} is required for this client.`);
      }
      if (!selected.has(metric) && value !== undefined) {
        throw new BadRequestException(
          `${field} is not enabled for this client.`,
        );
      }
    }
  }
}
