/**
 * audit-dev-api / validate.ts — Args validation (Zod + filesystem sanity).
 */
import { existsSync, statSync } from 'node:fs'
import path from 'node:path'
import { AuditDevApiArgsSchema, type ArgsValidationResult } from './types.js'

export function validateArgs(raw: unknown): ArgsValidationResult {
  const parsed = AuditDevApiArgsSchema.safeParse(raw)
  if (!parsed.success) {
    return {
      valid: false,
      args: null,
      errors: parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`),
    }
  }

  const args = parsed.data
  const errors: string[] = []

  // backendPath must exist as a directory.
  const beAbs = path.resolve(args.backendPath)
  if (!existsSync(beAbs)) {
    errors.push(`backendPath does not exist: ${beAbs}`)
  } else if (!statSync(beAbs).isDirectory()) {
    errors.push(`backendPath is not a directory: ${beAbs}`)
  }

  // modulePath must exist as a directory.
  const mpAbs = path.resolve(args.modulePath)
  if (!existsSync(mpAbs)) {
    errors.push(`modulePath does not exist: ${mpAbs}`)
  } else if (!statSync(mpAbs).isDirectory()) {
    errors.push(`modulePath is not a directory: ${mpAbs}`)
  }

  // Rule codes must look like DEV-API-NNN.
  for (const ruleId of args.rules) {
    if (!/^DEV-API-\d{3}$/.test(ruleId)) {
      errors.push(`rule id "${ruleId}" must match /^DEV-API-\\d{3}$/ (e.g. "DEV-API-010")`)
    }
  }

  return { valid: errors.length === 0, args, errors }
}
