import type { ZodIssue, ZodType } from "zod";

export class FormValidationError extends Error {
  fieldErrors: Record<string, string>;
  issues: ZodIssue[];

  constructor(issues: ZodIssue[]) {
    super(issues[0]?.message || "表单校验失败");
    this.name = "FormValidationError";
    this.issues = issues;
    this.fieldErrors = issues.reduce<Record<string, string>>((errors, issue) => {
      const field = issue.path.join(".");
      if (field && !errors[field]) {
        errors[field] = issue.message;
      }
      return errors;
    }, {});
  }
}

export function parseForm<TValue>(schema: ZodType<TValue>, value: unknown): TValue {
  const result = schema.safeParse(value);
  if (result.success) {
    return result.data;
  }
  throw new FormValidationError(result.error.issues);
}
