import { z } from "zod"

import { Permissions } from "@/shared/types/permissions"

/** All valid permission strings, used to validate the permission list on assignment. */
const ALL_PERMISSION_VALUES = Object.values(Permissions) as readonly string[]

export const CreateRoleSchema = z.object({
  name: z
    .string()
    .min(2, "Role name must be at least 2 characters")
    .max(50, "Role name must be at most 50 characters")
    .regex(/^[a-z0-9_]+$/, "Role name must be lowercase letters, digits, and underscores only"),
  description: z.string().max(255).optional().nullable(),
})

export const UpdateRoleSchema = z.object({
  name: z
    .string()
    .min(2)
    .max(50)
    .regex(/^[a-z0-9_]+$/)
    .optional(),
  description: z.string().max(255).optional().nullable(),
})

export const SetRolePermissionsSchema = z.object({
  roleId: z.string().min(1),
  permissions: z
    .array(z.string())
    .refine(
      (perms) => perms.every((p) => ALL_PERMISSION_VALUES.includes(p)),
      { message: "One or more permissions are invalid" }
    ),
})

export const AssignUserRolesSchema = z.object({
  userId: z.string().min(1),
  roleNames: z
    .array(z.string().min(1))
    .min(0, "Role list cannot be undefined (use empty array to clear)"),
})
