/**
 * validate.ts — Validation structurelle (Zod) + règles métier.
 * Ne connaît pas la DB, ne persiste rien.
 */
import { InitSpecSchema, type InitSpec } from './types.js';

export interface ValidationResult {
  valid: boolean;
  data?: InitSpec;
  blockers: string[];
  warnings: string[];
}

export function validate(raw: unknown): ValidationResult {
  const blockers: string[] = [];
  const warnings: string[] = [];

  // ── Structural validation (Zod) ─────────────────────────
  const parsed = InitSpecSchema.safeParse(raw);
  if (!parsed.success) {
    for (const issue of parsed.error.issues) {
      blockers.push(`[${issue.path.join('.')}] ${issue.message}`);
    }
    return { valid: false, blockers, warnings };
  }

  const data = parsed.data;

  // ── Business rules ──────────────────────────────────────

  // Rule: mode must be valid
  if (!['organized', 'simple', 'disabled'].includes(data.mode)) {
    blockers.push(`Invalid worktree mode: ${data.mode}`);
  }

  // Rule: if url is provided, it must be a valid git URL
  if (data.url) {
    if (!data.url.includes('github.com') && !data.url.includes('dev.azure.com') && !data.url.includes('gitlab.com')) {
      warnings.push(`URL provider not recognized: ${data.url}`);
    }
  }

  // Rule: if name is provided, it must be a valid git repo name
  if (data.name) {
    if (!/^[a-z0-9][a-z0-9._-]*$/i.test(data.name)) {
      blockers.push(`Invalid repository name: ${data.name}`);
    }
  }

  return {
    valid: blockers.length === 0,
    data,
    blockers,
    warnings,
  };
}
