#!/usr/bin/env ts-node
/**
 * Fix remaining TypeScript errors in test files
 */

import * as fs from 'fs';
import * as path from 'path';

// Recursively get all test files
function getAllTestFiles(dir: string, fileList: string[] = []): string[] {
  const files = fs.readdirSync(dir);

  for (const file of files) {
    const filePath = path.join(dir, file);
    const stat = fs.statSync(filePath);

    if (stat.isDirectory()) {
      getAllTestFiles(filePath, fileList);
    } else if (file.endsWith('.test.ts') || file.endsWith('.e2e.test.ts')) {
      fileList.push(filePath);
    }
  }

  return fileList;
}

const srcDir = path.join(__dirname, '../src');
const testFiles = getAllTestFiles(srcDir);

let totalChanges = 0;

for (const filePath of testFiles) {
  const file = path.basename(filePath);
  let content = fs.readFileSync(filePath, 'utf-8');
  let changes = 0;

  // Fix 1: Malformed executionPlan with nested structure
  // Pattern: executionPlan: { components: [], services: [] , executionPlan: { workflow, componentPlans: new Map() } }
  // Replace with: executionPlan: { workflow, componentPlans: new Map() }
  const malformedExecutionPlanRegex = /executionPlan:\s*\{\s*components:\s*\[\],\s*services:\s*\[\]\s*,\s*executionPlan:\s*\{\s*workflow,\s*componentPlans:\s*new\s+Map\(\)\s*\}\s*\}/g;
  const oldContent1 = content;
  content = content.replace(malformedExecutionPlanRegex, 'executionPlan: { workflow, componentPlans: new Map() }');
  if (content !== oldContent1) {
    const count = (oldContent1.match(malformedExecutionPlanRegex) || []).length;
    changes += count;
  }

  // Fix 2: Fix Field type missing properties - add defaults for required fields
  // Pattern: { type: 'string', required: true }
  // Replace with: { type: 'string', required: true, unique: false, system_field: false, exclude_from_forms: false }
  const fieldWithoutDefaultsRegex = /\{\s*type:\s*['"](\w+)['"],\s*required:\s*(true|false)\s*\}/g;
  const oldContent2 = content;
  content = content.replace(fieldWithoutDefaultsRegex, (match, type, required) => {
    changes++;
    return `{ type: '${type}', required: ${required}, unique: false, system_field: false, exclude_from_forms: false }`;
  });

  // Fix 3: Add missing 'auth' property to Endpoint definitions
  // Pattern: { path: '/users', method: 'GET', component: 'users', description: '...' }
  // Replace with: { path: '/users', method: 'GET', component: 'users', auth: 'none', description: '...' }
  const endpointWithoutAuthRegex = /\{\s*path:\s*'([^']+)',\s*method:\s*'(GET|POST|PUT|DELETE|PATCH)',\s*component:\s*'([^']+)',\s*description:/g;
  const oldContent3 = content;
  content = content.replace(endpointWithoutAuthRegex, (match, path, method, component) => {
    changes++;
    return `{ path: '${path}', method: '${method}', component: '${component}', auth: 'none' as const, description:`;
  });

  // Fix 4: Fix database config type (should be connection string, not object)
  // Pattern: database: { type: 'postgresql', version: '15' }
  // Replace with: database: 'postgresql://localhost/test' (or comment it out)
  const databaseObjectRegex = /database:\s*\{[^}]*type:\s*['"](\w+)['"][^}]*\},?\s*\n/g;
  const oldContent4 = content;
  content = content.replace(databaseObjectRegex, () => {
    changes++;
    return ''; // Remove the database config object
  });

  // Fix 5: Fix Table missing description property
  // Pattern: { name: 'users', required_fields: [...] }
  // Replace with: { name: 'users', description: 'Table description', required_fields: [...] }
  const tableWithoutDescRegex = /\{\s*name:\s*'([^']+)',\s*required_fields:/g;
  const oldContent5 = content;
  content = content.replace(tableWithoutDescRegex, (match, name) => {
    changes++;
    return `{ name: '${name}', description: '${name} table', required_fields:`;
  });

  if (changes > 0) {
    fs.writeFileSync(filePath, content, 'utf-8');
    console.log(`✓ Fixed ${changes} issues in ${file}`);
    totalChanges += changes;
  }
}

console.log(`\n✅ Total: Fixed ${totalChanges} issues across ${testFiles.length} files`);
