import { z } from 'zod';

const nullableTrimmedString = z
  .string()
  .trim()
  .min(1)
  .optional()
  .nullable()
  .transform((value) => value ?? null);

const nullableNumber = z
  .coerce.number()
  .finite()
  .optional()
  .nullable()
  .transform((value) => value ?? null);

const nullableBoolean = z
  .boolean()
  .optional()
  .nullable()
  .transform((value) => value ?? null);

export const approvalMatrixBaseSchema = z
  .object({
    entityType: z.string().trim().min(1),
    workflowId: z.string().trim().min(1),
    branchId: nullableTrimmedString,
    productType: nullableTrimmedString,
    minAmount: nullableNumber,
    maxAmount: nullableNumber,
    currency: nullableTrimmedString,
    priority: z.number().int(),
    isDefault: z.boolean(),
    isActive: z.boolean(),
    description: nullableTrimmedString
  })
  .superRefine((value, ctx) => {
    if (
      value.minAmount !== null &&
      value.maxAmount !== null &&
      value.minAmount > value.maxAmount
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['minAmount'],
        message: 'minAmount must be less than or equal to maxAmount'
      });
    }
  });

export const createApprovalMatrixSchema = approvalMatrixBaseSchema;

export const updateApprovalMatrixSchema = z
  .object({
    entityType: z.string().trim().min(1).optional(),
    workflowId: z.string().trim().min(1).optional(),
    branchId: nullableTrimmedString.optional(),
    productType: nullableTrimmedString.optional(),
    minAmount: nullableNumber.optional(),
    maxAmount: nullableNumber.optional(),
    currency: nullableTrimmedString.optional(),
    priority: z.number().int().optional(),
    isDefault: nullableBoolean.optional(),
    isActive: nullableBoolean.optional(),
    description: nullableTrimmedString.optional()
  })
  .superRefine((value, ctx) => {
    if (
      value.minAmount !== undefined &&
      value.maxAmount !== undefined &&
      value.minAmount !== null &&
      value.maxAmount !== null &&
      value.minAmount > value.maxAmount
    ) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ['minAmount'],
        message: 'minAmount must be less than or equal to maxAmount'
      });
    }
  });

export type CreateApprovalMatrixInput = z.infer<typeof createApprovalMatrixSchema>;
export type UpdateApprovalMatrixInput = z.infer<typeof updateApprovalMatrixSchema>;
