import type { PlanRules } from '@repo/api-contract';
import { planRulesSchema } from '@repo/api-contract';

export type PlanUsageSnapshot = {
  courtsCount: number;
  bookingsToday: number;
  activeUsersCount?: number;
};

export type PlanViolationCode =
  | 'MAX_COURTS_REACHED'
  | 'MAX_BOOKINGS_PER_DAY_REACHED'
  | 'MAX_ACTIVE_USERS_REACHED';

export type PlanViolation = {
  code: PlanViolationCode;
  message: string;
};

export function parsePlanRules(input: unknown): PlanRules {
  return planRulesSchema.parse(input);
}

export function evaluatePlanUsage(rules: PlanRules, usage: PlanUsageSnapshot): PlanViolation[] {
  const violations: PlanViolation[] = [];

  if (usage.courtsCount >= rules.limits.maxCourts) {
    violations.push({
      code: 'MAX_COURTS_REACHED',
      message: `El plan permite hasta ${rules.limits.maxCourts} canchas.`,
    });
  }

  if (usage.bookingsToday >= rules.limits.maxBookingsPerDay) {
    violations.push({
      code: 'MAX_BOOKINGS_PER_DAY_REACHED',
      message: `El plan permite hasta ${rules.limits.maxBookingsPerDay} turnos por dia.`,
    });
  }

  if (
    typeof rules.limits.maxActiveUsers === 'number' &&
    typeof usage.activeUsersCount === 'number' &&
    usage.activeUsersCount >= rules.limits.maxActiveUsers
  ) {
    violations.push({
      code: 'MAX_ACTIVE_USERS_REACHED',
      message: `El plan permite hasta ${rules.limits.maxActiveUsers} usuarios activos.`,
    });
  }

  return violations;
}

export function isFeatureEnabled(rules: PlanRules, feature: keyof PlanRules['features']): boolean {
  return rules.features[feature];
}
