#!/usr/bin/env node

/**
 * Pre-commit Hook: Validate Prisma Relation Usage
 * Prevents billing tab issues by checking:
 * 1. Correct relation names are used
 * 2. No camelCase where snake_case is required
 * 3. NextAuth v5 syntax is used
 *
 * Exit code 1 if validation fails (blocks commit)
 */

import { readFileSync, readdirSync, statSync } from 'fs';
import { join, extname } from 'path';

const errors = [];
const warnings = [];

// Colors for terminal output
const RED = '\x1b[31m';
const YELLOW = '\x1b[33m';
const GREEN = '\x1b[32m';
const RESET = '\x1b[0m';

console.log('\n🔍 Validating Prisma relation usage...\n');

/**
 * Get all TypeScript files in app/api
 */
function getAllApiFiles(dir, fileList = []) {
  const files = readdirSync(dir);

  files.forEach(file => {
    const filePath = join(dir, file);
    const stat = statSync(filePath);

    if (stat.isDirectory()) {
      getAllApiFiles(filePath, fileList);
    } else if (extname(file) === '.ts' && !file.includes('.test.')) {
      fileList.push(filePath);
    }
  });

  return fileList;
}

/**
 * Check for common Prisma relation mistakes
 */
function validateFile(filePath) {
  const content = readFileSync(filePath, 'utf-8');
  const fileName = filePath.replace(process.cwd() + '/', '');

  // Skip files that don't use Prisma
  if (!content.includes('prisma.subscriptions')) {
    return;
  }

  console.log(`📄 Checking ${fileName}...`);

  // Rule 1: Check for wrong "billingHistory" (should be "billing_history")
  const wrongBillingHistoryRegex = /include:\s*\{[^}]*billingHistory\s*:/g;
  if (wrongBillingHistoryRegex.test(content)) {
    errors.push({
      file: fileName,
      rule: 'Wrong relation name: "billingHistory"',
      fix: 'Use "billing_history" (snake_case) in include statement',
    });
  }

  // Rule 2: Check for wrong "user" in WHERE clause (should be "users")
  const whereUserRegex = /where:\s*\{[^}]*\buser:\s*\{[^}]*email/g;
  if (whereUserRegex.test(content) && content.includes('prisma.subscriptions')) {
    errors.push({
      file: fileName,
      rule: 'Wrong relation name in WHERE clause: "user"',
      fix: 'Use "users" (plural) when querying subscriptions by user',
    });
  }

  // Rule 3: Check for subscription.billingHistory (should be billing_history)
  const wrongAccessRegex = /subscription\.billingHistory/g;
  if (wrongAccessRegex.test(content)) {
    errors.push({
      file: fileName,
      rule: 'Wrong property access: "subscription.billingHistory"',
      fix: 'Use "subscription.billing_history" (snake_case)',
    });
  }

  // Rule 4: Check for subscription.user (should be subscription.users)
  const wrongUserAccessRegex = /subscription\.user\.(id|email|name)/g;
  if (wrongUserAccessRegex.test(content)) {
    errors.push({
      file: fileName,
      rule: 'Wrong property access: "subscription.user"',
      fix: 'Use "subscription.users" (plural)',
    });
  }

  // Rule 5: Check for NextAuth v4 syntax
  if (content.includes('getServerSession') || content.includes('authOptions')) {
    warnings.push({
      file: fileName,
      rule: 'Using NextAuth v4 syntax',
      fix: 'Use NextAuth v5: import { auth } from "@/lib/auth"; const session = await auth();',
    });
  }

  // Rule 6: Positive check - Verify correct usage exists
  if (content.includes('billing_history:') && content.includes('users:')) {
    console.log(`  ${GREEN}✓${RESET} Correct relation names found`);
  }
}

// Run validation
try {
  const apiDir = join(process.cwd(), 'app/api');
  const apiFiles = getAllApiFiles(apiDir);

  apiFiles.forEach(validateFile);

  // Report results
  console.log('\n' + '='.repeat(60));

  if (errors.length > 0) {
    console.log(`\n${RED}❌ VALIDATION FAILED${RESET}\n`);

    errors.forEach((error, index) => {
      console.log(`${RED}Error ${index + 1}:${RESET}`);
      console.log(`  File: ${error.file}`);
      console.log(`  Rule: ${error.rule}`);
      console.log(`  Fix:  ${error.fix}\n`);
    });

    console.log(`${RED}Please fix ${errors.length} error(s) before committing.${RESET}\n`);
    process.exit(1);
  }

  if (warnings.length > 0) {
    console.log(`\n${YELLOW}⚠️  WARNINGS${RESET}\n`);

    warnings.forEach((warning, index) => {
      console.log(`${YELLOW}Warning ${index + 1}:${RESET}`);
      console.log(`  File: ${warning.file}`);
      console.log(`  Rule: ${warning.rule}`);
      console.log(`  Fix:  ${warning.fix}\n`);
    });
  }

  console.log(`${GREEN}✅ Prisma relation validation passed!${RESET}\n`);
  process.exit(0);

} catch (error) {
  console.error(`${RED}❌ Validation script error:${RESET}`, error);
  process.exit(1);
}
