import { z } from 'zod';

// branchId may be null = "All branches" (restaurant-wide). The route only
// allows null for the owner role; pinned staff/managers get a 403 there.
export const switchBranchSchema = z.object({
  branchId: z.string().uuid('branchId must be a valid UUID').nullable(),
});

export type SwitchBranchInput = z.infer<typeof switchBranchSchema>;

const slugFieldSchema = z.string()
  .min(2)
  .max(64)
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, 'Slug must be lowercase letters, digits and hyphens');

function getValidIanaTzSet(): Set<string> {
  try {
    const intlAny = Intl as unknown as { supportedValuesOf?: (k: string) => string[] };
    const zones = intlAny.supportedValuesOf?.('timeZone');
    if (zones && zones.length > 0) return new Set(zones);
  } catch {
    // fall through to fallback
  }
  return new Set<string>(); // empty = skip membership check on old runtimes
}

const IANA_TZ_SET = getValidIanaTzSet();

const timezoneSchema = z
  .string()
  .transform(v => v.trim())
  .refine(v => v.length > 0, 'Timezone must be a non-empty string')
  .refine(
    v => IANA_TZ_SET.size === 0 || IANA_TZ_SET.has(v),
    'Timezone must be a valid IANA timezone identifier (e.g. America/New_York)',
  )
  .optional();

export const createBranchSchema = z.object({
  name: z.string().min(1, 'Branch name is required'),
  address: z.string().nullable().optional(),
  phone: z.string().nullable().optional(),
  hours: z.record(z.string(), z.any()).optional(),
  timezone: timezoneSchema,
  is_active: z.boolean().optional(),
  slug: slugFieldSchema.optional(),
});

export const updateBranchSchema = z.object({
  name: z.string().min(1).optional(),
  address: z.string().nullable().optional(),
  phone: z.string().nullable().optional(),
  hours: z.record(z.string(), z.any()).optional(),
  timezone: timezoneSchema,
  is_active: z.boolean().optional(),
  smtp_host: z.string().nullable().optional(),
  smtp_port: z.number().int().nullable().optional(),
  smtp_user: z.string().nullable().optional(),
  smtp_pass: z.string().nullable().optional(),
  smtp_from: z.string().nullable().optional(),
  slug: slugFieldSchema.optional(),
  storefront_enabled: z.boolean().optional(),
  accepts_dine_in: z.boolean().optional(),
  accepts_takeaway: z.boolean().optional(),
  accepts_delivery: z.boolean().optional(),
  min_order_value: z.number().min(0).max(100000).optional(),
  storefront_message: z.string().max(280).nullable().optional(),
  qr_style_json: z.record(z.string(), z.any()).optional(),
  quiet_hours_enabled: z.boolean().optional(),
  quiet_hours_start: z.number().int().min(0).max(23).optional(),
  quiet_hours_end:   z.number().int().min(0).max(23).optional(),
  /**
   * WhatsApp per-WABA send rate cap (msgs/sec). Operators set this to match
   * their Meta WABA business tier. Default 10 = safe for unverified accounts.
   * Verified Standard tier ≈ 80 msg/s; Higher tiers ≈ 1000+ msg/s.
   */
  whatsapp_send_rate: z.number().int().min(1).max(1000).optional(),
});

export type CreateBranchInput = z.infer<typeof createBranchSchema>;
export type UpdateBranchInput = z.infer<typeof updateBranchSchema>;
