import { z } from 'zod'

const PermissionKeySchema = z.string().min(1).max(100)

export const OrgRoleParamsSchema = z
  .object({
    orgId: z.string().uuid(),
    roleId: z.string().uuid()
  })
  .strict()

export const OrgRolesParamsSchema = z
  .object({
    orgId: z.string().uuid()
  })
  .strict()

export const MembershipRoleParamsSchema = z
  .object({
    membershipId: z.string().min(1),
    roleId: z.string().uuid()
  })
  .strict()

export const MembershipParamsSchema = z
  .object({
    membershipId: z.string().min(1)
  })
  .strict()

export const CreateOrgRoleRequestSchema = z
  .object({
    name: z.string().min(1).max(100).trim(),
    slug: z
      .string()
      .min(1)
      .max(100)
      .regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, 'Role slug must be lowercase letters, numbers, dashes, or underscores'),
    description: z.string().max(500).trim().optional(),
    permissionKeys: z.array(PermissionKeySchema).default([])
  })
  .strict()

export const UpdateOrgRoleRequestSchema = z
  .object({
    name: z.string().min(1).max(100).trim().optional(),
    slug: z
      .string()
      .min(1)
      .max(100)
      .regex(/^[a-z0-9]+(?:[-_][a-z0-9]+)*$/, 'Role slug must be lowercase letters, numbers, dashes, or underscores')
      .optional(),
    description: z.string().max(500).trim().nullable().optional(),
    permissionKeys: z.array(PermissionKeySchema).optional()
  })
  .strict()
  .refine(
    (data) =>
      data.name !== undefined ||
      data.slug !== undefined ||
      data.description !== undefined ||
      data.permissionKeys !== undefined,
    { message: 'At least one field must be provided' }
  )

export const AssignMembershipRoleRequestSchema = z
  .object({
    roleId: z.string().uuid()
  })
  .strict()

export type OrgRoleParams = z.infer<typeof OrgRoleParamsSchema>
export type OrgRolesParams = z.infer<typeof OrgRolesParamsSchema>
export type MembershipRoleParams = z.infer<typeof MembershipRoleParamsSchema>
export type MembershipParams = z.infer<typeof MembershipParamsSchema>
export type CreateOrgRoleInput = z.infer<typeof CreateOrgRoleRequestSchema>
export type UpdateOrgRoleInput = z.infer<typeof UpdateOrgRoleRequestSchema>
export type AssignMembershipRoleInput = z.infer<typeof AssignMembershipRoleRequestSchema>
