#!/usr/bin/env tsx
/**
 * Contract Testing Integration Script
 * 
 * This script runs all contract tests in the correct order:
 * 1. API contract validation
 * 2. Type generation
 * 3. Website contract consumption tests
 * 4. Compatibility verification
 */

import { execSync } from 'child_process';
import * as fs from 'fs/promises';
import * as path from 'path';

const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  red: '\x1b[31m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
  dim: '\x1b[2m'
};

async function runContractTests(): Promise<void> {
  console.log(`${colors.cyan}🚀 Starting Contract Testing Suite${colors.reset}\n`);

  const steps = [
    {
      name: 'API Contract Validation',
      command: 'npm run test:api:contracts',
      description: 'Validate API DTOs and OpenAPI spec integrity'
    },
    {
      name: 'Generate OpenAPI Spec',
      command: 'npm run api:generate-spec',
      description: 'Generate OpenAPI specification from DTOs'
    },
    {
      name: 'Generate TypeScript Types',
      command: 'npm run api:generate-types',
      description: 'Generate TypeScript types for website'
    },
    {
      name: 'Contract Compatibility Check',
      command: 'npm run test:contract:compatibility',
      description: 'Check for breaking changes in contracts'
    },
    {
      name: 'Website Type Checking',
      command: 'npm run website:type-check',
      description: 'Verify website can consume generated types'
    }
  ];

  for (let i = 0; i < steps.length; i++) {
    const step = steps[i];
    console.log(`${colors.yellow}${i + 1}/${steps.length} ${step.name}${colors.reset}`);
    console.log(`${colors.dim}   ${step.description}${colors.reset}`);
    
    try {
      execSync(step.command, { 
        stdio: 'inherit',
        env: { ...process.env, FORCE_COLOR: 'true' }
      });
      console.log(`${colors.green}   ✅ ${step.name} completed${colors.reset}\n`);
    } catch (error) {
      console.log(`${colors.red}   ❌ ${step.name} failed${colors.reset}\n`);
      console.log(`${colors.red}Contract testing suite failed at step: ${step.name}${colors.reset}`);
      process.exit(1);
    }
  }

  console.log(`${colors.green}🎉 All contract tests passed!${colors.reset}`);
  console.log(`${colors.green}✅ Contracts are compatible and validated${colors.reset}`);
}

// Run if called directly
if (require.main === module) {
  runContractTests().catch(error => {
    console.error(`${colors.red}❌ Contract testing suite failed:${colors.reset}`, error);
    process.exit(1);
  });
}