import { z } from 'zod';

function normalizeWorkflowCode(value: string) {
  return value
    .trim()
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '');
}

const nullableTrimmedString = z
  .string()
  .trim()
  .optional()
  .nullable()
  .transform((value) => {
    if (!value) {
      return null;
    }
    return value;
  });

export const approvalWorkflowFilterSchema = z.object({
  entityType: z.string().trim().optional(),
  activeOnly: z
    .union([z.literal('true'), z.literal('false')])
    .optional()
    .transform((value) => value === 'true')
});

export const createApprovalWorkflowSchema = z.object({
  code: z
    .string()
    .min(1)
    .transform((value) => normalizeWorkflowCode(value))
    .refine((value) => value.length > 0, {
      message: 'code is required'
    }),
  name: z.string().trim().min(1),
  entityType: z.string().trim().min(1),
  description: nullableTrimmedString,
  isActive: z.boolean().optional()
});

export const updateApprovalWorkflowSchema = z.object({
  code: z
    .string()
    .min(1)
    .optional()
    .transform((value) => (value ? normalizeWorkflowCode(value) : value)),
  name: z.string().trim().min(1).optional(),
  entityType: z.string().trim().min(1).optional(),
  description: nullableTrimmedString.optional()
});

export type ApprovalWorkflowFiltersInput = z.infer<typeof approvalWorkflowFilterSchema>;
export type CreateApprovalWorkflowInput = z.infer<typeof createApprovalWorkflowSchema>;
export type UpdateApprovalWorkflowInput = z.infer<typeof updateApprovalWorkflowSchema>;
