/**
 * Script to verify specific user data
 * Usage: npx ts-node verify-user-data.ts gara2222ge@support.com
 */

import { PrismaClient } from './lib/generated/prisma';

const prisma = new PrismaClient();

async function verifyUserData(email: string) {
  console.log('\n=== DATABASE INTEGRITY CHECK ===\n');
  console.log(`Checking user: ${email}\n`);

  try {
    // Fetch user with all relationships
    const user = await prisma.user.findUnique({
      where: { email: email.toLowerCase() },
      include: {
        subscriptions: true,
        auditLogs: {
          orderBy: { createdAt: 'desc' },
          take: 10
        }
      }
    });

    if (!user) {
      console.log('ERROR: User not found in database\n');
      return;
    }

    // User Information
    console.log('USER INFORMATION:');
    console.log('================');
    console.log(`ID: ${user.id}`);
    console.log(`Email: ${user.email}`);
    console.log(`Name: ${user.name}`);
    console.log(`Email Verified: ${user.emailVerified ? user.emailVerified.toISOString() : 'NOT VERIFIED'}`);
    console.log(`Created: ${user.createdAt.toISOString()}`);
    console.log(`Updated: ${user.updatedAt.toISOString()}`);
    console.log(`Onboarding Complete: ${user.onboardingComplete ? 'YES' : 'NO'}`);
    console.log();

    // Pricing Selection
    console.log('PRICING SELECTION:');
    console.log('=================');
    console.log(`Selected Package: ${user.selectedPackage || 'NOT SET'}`);
    console.log();

    // Goals
    console.log('USER GOALS:');
    console.log('===========');
    if (user.goals && Array.isArray(user.goals)) {
      (user.goals as string[]).forEach((goal, index) => {
        console.log(`${index + 1}. ${goal}`);
      });
    } else {
      console.log('No goals set');
    }
    console.log();

    // Company Information
    console.log('COMPANY INFORMATION:');
    console.log('===================');
    console.log(`Company Name: ${user.companyName || 'NOT SET'}`);
    console.log(`Industry: ${user.industry || 'NOT SET'}`);
    console.log(`Company Size: ${user.companySize || 'NOT SET'}`);
    console.log(`Country: ${user.country || 'NOT SET'}`);
    console.log(`City: ${user.city || 'NOT SET'}`);
    console.log(`Phone: ${user.phoneNumber || 'NOT SET'}`);
    console.log(`Website: ${user.website || 'NOT SET'}`);
    console.log(`Address: ${user.address || 'NOT SET'}`);
    console.log();

    // Stripe Information
    console.log('STRIPE INFORMATION:');
    console.log('==================');
    console.log(`Stripe Customer ID: ${user.stripeCustomerId || 'NOT SET'}`);
    console.log();

    // Subscriptions
    console.log('SUBSCRIPTIONS:');
    console.log('=============');
    if (user.subscriptions.length === 0) {
      console.log('No subscriptions found');
    } else {
      user.subscriptions.forEach((sub, index) => {
        console.log(`\nSubscription ${index + 1}:`);
        console.log(`  ID: ${sub.id}`);
        console.log(`  Stripe Subscription ID: ${sub.stripeSubscriptionId}`);
        console.log(`  Stripe Price ID: ${sub.stripePriceId}`);
        console.log(`  Tier ID: ${sub.tierId}`);
        console.log(`  Status: ${sub.status}`);
        console.log(`  Billing Period: ${sub.billingPeriod}`);
        console.log(`  Current Period End: ${sub.currentPeriodEnd.toISOString()}`);
        console.log(`  Trial Ends At: ${sub.trialEndsAt ? sub.trialEndsAt.toISOString() : 'N/A'}`);
        console.log(`  Cancel At Period End: ${sub.cancelAtPeriodEnd ? 'YES' : 'NO'}`);
        console.log(`  Payment Failure Count: ${sub.paymentFailureCount}`);
        console.log(`  Created: ${sub.createdAt.toISOString()}`);
        console.log(`  Updated: ${sub.updatedAt.toISOString()}`);
      });
    }
    console.log();

    // Recent Audit Logs
    console.log('RECENT AUDIT LOGS (Last 10):');
    console.log('============================');
    if (user.auditLogs.length === 0) {
      console.log('No audit logs found');
    } else {
      user.auditLogs.forEach((log, index) => {
        console.log(`\n${index + 1}. ${log.action}`);
        console.log(`   Type: ${log.type}`);
        console.log(`   Success: ${log.success ? 'YES' : 'NO'}`);
        console.log(`   IP: ${log.ip}`);
        console.log(`   Time: ${log.createdAt.toISOString()}`);
        if (log.metadata) {
          console.log(`   Metadata: ${JSON.stringify(log.metadata, null, 2)}`);
        }
      });
    }
    console.log();

    // Data Consistency Checks
    console.log('DATA CONSISTENCY CHECKS:');
    console.log('=======================');
    const checks = [];

    // Check 1: Email verified
    if (user.emailVerified) {
      checks.push({ check: 'Email Verified', status: 'PASS', value: 'Yes' });
    } else {
      checks.push({ check: 'Email Verified', status: 'FAIL', value: 'No' });
    }

    // Check 2: Selected package set
    if (user.selectedPackage) {
      checks.push({ check: 'Selected Package', status: 'PASS', value: user.selectedPackage });
    } else {
      checks.push({ check: 'Selected Package', status: 'WARN', value: 'Not set' });
    }

    // Check 3: Company info complete
    const companyInfoComplete = user.companyName && user.industry && user.companySize;
    checks.push({
      check: 'Company Info Complete',
      status: companyInfoComplete ? 'PASS' : 'WARN',
      value: companyInfoComplete ? 'Yes' : 'Incomplete'
    });

    // Check 4: Goals set
    const goalsSet = user.goals && Array.isArray(user.goals) && user.goals.length > 0;
    checks.push({
      check: 'Goals Set',
      status: goalsSet ? 'PASS' : 'WARN',
      value: goalsSet ? `${(user.goals as string[]).length} goals` : 'Not set'
    });

    // Check 5: Onboarding complete
    checks.push({
      check: 'Onboarding Complete',
      status: user.onboardingComplete ? 'PASS' : 'FAIL',
      value: user.onboardingComplete ? 'Yes' : 'No'
    });

    // Check 6: Stripe customer created
    checks.push({
      check: 'Stripe Customer',
      status: user.stripeCustomerId ? 'PASS' : 'WARN',
      value: user.stripeCustomerId ? 'Created' : 'Not created'
    });

    // Check 7: Subscription exists
    const hasSubscription = user.subscriptions.length > 0;
    checks.push({
      check: 'Subscription Exists',
      status: hasSubscription ? 'PASS' : 'WARN',
      value: hasSubscription ? `${user.subscriptions.length} subscription(s)` : 'None'
    });

    // Check 8: Tier consistency
    if (hasSubscription && user.selectedPackage) {
      const tierMatch = user.subscriptions.some(sub => sub.tierId === user.selectedPackage);
      checks.push({
        check: 'Tier Consistency',
        status: tierMatch ? 'PASS' : 'FAIL',
        value: tierMatch ? 'Matching' : 'Mismatch'
      });
    }

    // Check 9: Timestamps valid
    const timestampsValid = user.createdAt <= user.updatedAt;
    checks.push({
      check: 'Timestamps Valid',
      status: timestampsValid ? 'PASS' : 'FAIL',
      value: timestampsValid ? 'Valid' : 'Invalid'
    });

    // Print checks
    checks.forEach(check => {
