import { z } from 'zod';

const nonNegativeInt = z.int().nonnegative();
const positiveInt = z.int().positive();

export const planFeatureFlagsSchema = z.object({
  onlinePayments: z.boolean().default(false),
  publicBookingPage: z.boolean().default(false),
  advancedReports: z.boolean().default(false),
  whatsappReminders: z.boolean().default(false),
  fixedSlots: z.boolean().default(false),
});

export const planRulesV1Schema = z.object({
  version: z.literal('v1'),
  limits: z.object({
    maxCourts: positiveInt,
    maxBookingsPerDay: positiveInt,
    maxActiveUsers: positiveInt.optional(),
    maxConcurrentBookingsPerSlot: positiveInt.optional(),
    maxSports: positiveInt.optional(),
  }),
  policies: z
    .object({
      maxAdvanceBookingDays: positiveInt.optional(),
      minCancellationNoticeHours: nonNegativeInt.optional(),
      allowOverbooking: z.boolean().default(false),
    })
    .default({ allowOverbooking: false }),
  features: planFeatureFlagsSchema.default({
    onlinePayments: false,
    publicBookingPage: false,
    advancedReports: false,
    whatsappReminders: false,
    fixedSlots: false,
  }),
});

export const planPriceOverrideSchema = z.object({
  amount: z.number().nonnegative(),
  currency: z.string().length(3),
});

export const planRulesV2Schema = planRulesV1Schema.extend({
  version: z.literal('v2'),
  pricing: z
    .object({
      overrides: z.record(z.string(), planPriceOverrideSchema),
    })
    .optional(),
});

export const planRulesSchema = z.discriminatedUnion('version', [
  planRulesV1Schema,
  planRulesV2Schema,
]);

export const planSchema = z.object({
  code: z.string().trim().min(1).max(10),
  name: z.string().trim().min(1).max(30),
  price: z.number().nonnegative(),
  lastUpdatedAt: z.string().datetime(),
  rules: planRulesSchema,
});

export const planSummarySchema = z.object({
  code: z.string().trim().min(1).max(10),
  name: z.string().trim().min(1).max(30),
  price: z.number().nonnegative(),
});

export const planLimitsSchema = z.object({
  maxCourts: positiveInt,
  maxBookingsPerDay: positiveInt,
  maxActiveUsers: positiveInt.optional(),
  maxConcurrentBookingsPerSlot: positiveInt.optional(),
  maxSports: positiveInt.optional(),
});

export const planWithFeaturesSchema = z.object({
  code: z.string().trim().min(1).max(10),
  name: z.string().trim().min(1).max(30),
  price: z.number().nonnegative(),
  currency: z.string().length(3),
  features: planFeatureFlagsSchema,
  limits: planLimitsSchema,
});

export type PlanFeatureFlags = z.infer<typeof planFeatureFlagsSchema>;
export type PlanRulesV1 = z.infer<typeof planRulesV1Schema>;
export type PlanRulesV2 = z.infer<typeof planRulesV2Schema>;
export type PlanRules = z.infer<typeof planRulesSchema>;
export type Plan = z.infer<typeof planSchema>;
export type PlanSummary = z.infer<typeof planSummarySchema>;
export type PlanWithFeatures = z.infer<typeof planWithFeaturesSchema>;
export type PlanLimits = z.infer<typeof planLimitsSchema>;
