import type { StandardSchemaV1 } from "@standard-schema/spec";

/**
 * Normalized validation issue with a simplified path.
 */
export interface ValidationIssue {
  /**
   * Path to the invalid value.
   */
  path?: (string | number)[];
  /**
   * Human-readable validation message.
   */
  message: string;
}

/**
 * Error thrown when Standard Schema validation fails.
 * Shared across client and server packages so `instanceof` checks work
 * regardless of which package threw the error.
 */
export class SchemaValidationError extends Error {
  /**
   * Normalized validation issues.
   */
  readonly issues: ReadonlyArray<ValidationIssue>;

  constructor(rawIssues: ReadonlyArray<StandardSchemaV1.Issue>) {
    const issues: ValidationIssue[] = rawIssues.map((i) => ({
      path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) as
        | (string | number)[]
        | undefined,
      message: i.message,
    }));
    const message = issues
      .map((i) =>
        i.path?.length ? `${i.path.join(".")}: ${i.message}` : i.message,
      )
      .join("; ");
    super(message);
    this.name = "SchemaValidationError";
    this.issues = issues;
  }
}
