import { z } from 'zod';

const CANONICAL_SECTIONS = [
  'dashboard',
  'orders', 'reservations',
  'ai_config', 'knowledge_base', 'chat_widget', 'conversations',
  'telephone', 'whatsapp',
  'menu', 'customers', 'loyalty', 'storefront',
  'marketing', 'gift_cards', 'coupons',
  'staff', 'branches', 'analytics', 'settings',
] as const;

const LEGACY_SECTIONS = [...CANONICAL_SECTIONS, 'bookings'] as const;

const crudPermsSchema = z.object({
  create: z.boolean(),
  read: z.boolean(),
  update: z.boolean(),
  delete: z.boolean(),
});

const permissionsObjectSchema = z.object({
  dashboard:     crudPermsSchema.optional(),
  orders:        crudPermsSchema.optional(),
  reservations:  crudPermsSchema.optional(),
  ai_config:     crudPermsSchema.optional(),
  knowledge_base:crudPermsSchema.optional(),
  chat_widget:   crudPermsSchema.optional(),
  conversations: crudPermsSchema.optional(),
  telephone:     crudPermsSchema.optional(),
  whatsapp:      crudPermsSchema.optional(),
  menu:          crudPermsSchema.optional(),
  customers:     crudPermsSchema.optional(),
  loyalty:       crudPermsSchema.optional(),
  storefront:    crudPermsSchema.optional(),
  marketing:     crudPermsSchema.optional(),
  gift_cards:    crudPermsSchema.optional(),
  coupons:       crudPermsSchema.optional(),
  staff:         crudPermsSchema.optional(),
  branches:      crudPermsSchema.optional(),
  analytics:     crudPermsSchema.optional(),
  settings:      crudPermsSchema.optional(),
}).strict();

const permissionsSchema = z.union([
  z.array(z.enum(LEGACY_SECTIONS)),
  permissionsObjectSchema,
]).optional();

export const createStaffSchema = z.object({
  branch_id: z.string().uuid().optional(),
  user_id: z.string().uuid().optional(),
  name: z.string().min(1, 'Name is required'),
  email: z.string().email().optional().or(z.literal('')),
  role: z.string().optional(),
  role_id: z.string().uuid().optional().nullable(),
  permissions: permissionsSchema,
  is_active: z.boolean().optional(),
});

export const updateStaffSchema = z.object({
  name: z.string().min(1).optional(),
  email: z.string().email().optional().or(z.literal('')),
  role: z.string().optional(),
  role_id: z.string().uuid().optional().nullable(),
  permissions: permissionsSchema,
  is_active: z.boolean().optional(),
});

export type CreateStaffInput = z.infer<typeof createStaffSchema>;
export type UpdateStaffInput = z.infer<typeof updateStaffSchema>;
