/**
 * audit-dev-tests — validate.ts
 */
import { existsSync, statSync } from 'node:fs'
import { AuditDevTestsSpecSchema, type AuditDevTestsSpec } from './types.js'

export interface ValidationResult {
  valid: boolean
  errors: string[]
  data?: AuditDevTestsSpec
}

export function validate(raw: unknown): ValidationResult {
  const parsed = AuditDevTestsSpecSchema.safeParse(raw)
  if (!parsed.success) {
    return {
      valid: false,
      errors: parsed.error.issues.map(i => `${i.path.join('.') || '(root)'}: ${i.message}`),
    }
  }
  const spec = parsed.data
  const errors: string[] = []

  if (!existsSync(spec.moduleDir) || !statSync(spec.moduleDir).isDirectory()) {
    errors.push(`moduleDir does not exist or is not a directory: ${spec.moduleDir}`)
  }
  if (!existsSync(spec.projectPath) || !statSync(spec.projectPath).isDirectory()) {
    errors.push(`projectPath does not exist or is not a directory: ${spec.projectPath}`)
  }

  return {
    valid: errors.length === 0,
    errors,
    data: errors.length === 0 ? spec : undefined,
  }
}
