import { z } from 'zod';

const CANONICAL_SECTIONS = ['dashboard', 'orders', 'reservations', 'menu', 'customers', 'conversations', 'staff', '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(),
  menu: crudPermsSchema.optional(),
  customers: crudPermsSchema.optional(),
  conversations: crudPermsSchema.optional(),
  staff: 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>;
