// 驗證 component.contract.yaml 所有必填欄位
// Requirements: 1.1, 1.2, 11.5

import { ComponentContractSchema } from '../types';
import type { ComponentContract } from '../types';

export interface ValidateContractResult {
  valid: boolean;
  missing_fields: string[];
  errors: string[];
  contract?: ComponentContract;
}

export function validateContract(raw: unknown): ValidateContractResult {
  const result = ComponentContractSchema.safeParse(raw);

  if (result.success) {
    return { valid: true, missing_fields: [], errors: [], contract: result.data };
  }

  const missing_fields: string[] = [];
  const errors: string[] = [];

  for (const issue of result.error.issues) {
    const path = issue.path.join('.');
    if (issue.code === 'invalid_type' && issue.received === 'undefined') {
      missing_fields.push(path || issue.message);
    } else {
      errors.push(path ? `${path}: ${issue.message}` : issue.message);
    }
  }

  return { valid: false, missing_fields, errors };
}
