/**
 * Example: Check .vns name availability before registering
 *
 * Run: npx ts-node examples/check-availability.ts
 */

import {
  checkVNSAvailability,
  validateVNSName,
  formatVNSName,
  resolver,
} from '../src/index.js';

async function main() {
  console.log('Vaultfire Name Service — Availability Check\n');

  const namesToCheck = [
    'my-new-agent',          // likely available
    'vaultfire-sentinel',    // taken
    'ab',                    // too short
    'this-name-is-way-too-long-to-be-valid-for-vns', // too long
    'vaultfire',             // reserved
    'invalid--name',         // consecutive hyphens
    '-starts-with-hyphen',   // invalid start
    'valid-agent-123',       // should be available
    'UPPERCASE',             // auto-lowercased
  ];

  for (const name of namesToCheck) {
    console.log(`Checking: "${name}"`);

    // First validate format locally (no network call)
    const validation = validateVNSName(name);
    if (!validation.valid) {
      console.log(`  ✗ Invalid format: ${validation.error}\n`);
      continue;
    }

    // Then check on-chain availability
    const availability = await checkVNSAvailability(name);
    const normalized = formatVNSName(name);

    if (availability.available) {
      console.log(`  ✓ ${normalized} is available!\n`);
    } else {
      let msg = `  ✗ ${normalized} is taken`;
      if (availability.takenBy) msg += ` by ${availability.takenBy.slice(0, 10)}...`;
      if (availability.takenOn) msg += ` on ${availability.takenOn}`;
      console.log(msg + '\n');
    }
  }

  // Using resolver convenience method
  console.log('Using resolver.checkAvailability():\n');
  const avail = await resolver.checkAvailability('my-awesome-bot');
  if (avail.available) {
    console.log(`"my-awesome-bot.vns" is available — you can register it!`);
  } else {
    console.log(`"my-awesome-bot.vns" is not available.`);
  }

  // Validate only (no network call)
  console.log('\nLocal validation only (no network):\n');
  const testNames = ['good-name', 'bad--name', 'x', 'valid123'];
  testNames.forEach(n => {
    const r = validateVNSName(n);
    console.log(`  "${n}" → ${r.valid ? `valid (normalized: "${r.normalized}")` : `invalid: ${r.error}`}`);
  });
}

main().catch(console.error);
