import type { ZodType } from 'zod'
import type { ProblemDetails } from '../api/problem'

export interface FormValidationFailure {
  summary: string
  fields: Record<string, string[]>
}

export type FormValidationResult<T> =
  | { success: true; data: T }
  | { success: false; error: FormValidationFailure }

/** Parse at the feature submit boundary; the generic screen shell stays presentation-only. */
export function validateFormSubmission<T>(schema: ZodType<T>, input: unknown): FormValidationResult<T> {
  const result = schema.safeParse(input)
  if (result.success) return result

  const fields: Record<string, string[]> = {}
  for (const issue of result.error.issues) {
    const field = issue.path.length > 0 ? issue.path.join('.') : '_form'
    fields[field] ??= []
    fields[field].push(issue.message)
  }
  return { success: false, error: { summary: '입력값을 확인해 주세요.', fields } }
}

export function mapProblemToFormFailure(problem: Pick<ProblemDetails, 'title' | 'detail' | 'errors'>): FormValidationFailure {
  return {
    summary: problem.detail?.trim() || problem.title,
    fields: Object.fromEntries(Object.entries(problem.errors ?? {}).map(([field, messages]) => [field, [...messages]]))
  }
}
