import {z} from 'zod';

export type ValidationResult =
  | {success: true}
  | {success: false; issues: string[]};

export const requiredString = z.string().min(1);
export const requiredInt = z.number().int();
export const numericString = z.string().regex(/^\d+$/);
export const requiredUserId = z.union([numericString, requiredInt]);

export const assetDBRequiredFieldsSchema = z
  .object({
    id: requiredInt,
    mimetype: requiredString,
    filename: requiredString,
    metadata: z.object({format: requiredString}).passthrough(),
  })
  .passthrough();

export const getValidationResult = (
  schema: z.ZodTypeAny,
  data: unknown,
): ValidationResult => {
  const parsed = schema.safeParse(data);
  if (parsed.success) {
    return {success: true};
  }

  return {
    success: false,
    issues: parsed.error.issues.map(
      issue => `${issue.path.join('.')}: ${issue.message}`,
    ),
  };
};
