const { PrismaClient } = require('@prisma/client');

const prisma = new PrismaClient();

async function testDatabaseConnection() {
  try {
    console.log('Testing database connection...');
    
    // Test basic connection
    await prisma.$connect();
    console.log('✅ Database connection successful');
    
    // Check if notification_templates table exists
    const tableInfo = await prisma.$queryRaw`
      SELECT COUNT(*) as count 
      FROM information_schema.tables 
      WHERE table_schema = DATABASE() 
      AND table_name = 'notification_templates'
    `;
    
    console.log('Table exists check:', tableInfo);
    
    // Check current data in the table
    const count = await prisma.notification_templates.count();
    console.log(`📊 Current templates count: ${count}`);
    
    // Fetch all templates to see what we have
    const templates = await prisma.notification_templates.findMany({
      select: {
        id: true,
        name: true,
        value: true,
        status: true,
        category: true,
        channels: true,
        created_at: true
      }
    });
    
    console.log('📝 Current templates:', JSON.stringify(templates, null, 2));
    
    return { success: true, count, templates };
    
  } catch (error) {
    console.error('❌ Database test failed:', error);
    return { success: false, error: error.message };
  } finally {
    await prisma.$disconnect();
  }
}

async function testAPILogic() {
  try {
    console.log('\n🧪 Testing API logic...');
    
    // Simulate the API endpoint logic
    const queryParams = {
      page: 1,
      limit: 10,
      sortBy: "created_at",
      sortOrder: "desc"
    };
    
    console.log('Query params:', queryParams);
    
    // Build where clause (same as API)
    const whereClause = {};
    
    // Calculate pagination
    const skip = (queryParams.page - 1) * queryParams.limit;
    
    // Get total count
    const totalCount = await prisma.notification_templates.count({
      where: whereClause
    });
    
    console.log(`📊 Total count: ${totalCount}`);
    
    // Fetch templates
    const templates = await prisma.notification_templates.findMany({
      where: whereClause,
      orderBy: {
        [queryParams.sortBy]: queryParams.sortOrder
      },
      skip: skip,
      take: queryParams.limit,
      select: {
        id: true,
        name: true,
        value: true,
        description: true,
        subject: true,
        category: true,
        channels: true,
        status: true,
        version: true,
        tags: true,
        is_personal: true,
        is_active: true,
        created_by: true,
        created_at: true,
        updated_at: true
      }
    });
    
    console.log(`📝 Fetched ${templates.length} templates`);
    
    // Format the response data (same as API)
    const formattedTemplates = templates.map(template => ({
      id: template.id,
      title: template.name,
      value: template.value,
      description: template.description,
      subject: template.subject,
      category: template.category,
      channels: template.channels || [],
      status: template.status,
      version: template.version,
      tags: template.tags ? template.tags.split(',').map(tag => tag.trim()) : [],
      isPersonal: template.is_personal,
      isActive: template.is_active,
      createdBy: template.created_by,
      createdAt: template.created_at,
      updatedAt: template.updated_at
    }));
    
    // Calculate pagination info
    const totalPages = Math.ceil(totalCount / queryParams.limit);
    const hasNextPage = queryParams.page < totalPages;
    const hasPrevPage = queryParams.page > 1;
    
    const apiResponse = {
      success: true,
      data: {
        templates: formattedTemplates,
        pagination: {
          page: queryParams.page,
          limit: queryParams.limit,
          totalCount,
          totalPages,
          hasNextPage,
          hasPrevPage
        }
      }
    };
    
    console.log('🚀 Simulated API Response structure:');
    console.log(`  success: ${apiResponse.success}`);
    console.log(`  data: ${apiResponse.data ? 'exists' : 'undefined'}`);
    console.log(`  data.templates: ${apiResponse.data?.templates ? `array with ${apiResponse.data.templates.length} items` : 'undefined'}`);
    console.log(`  data.pagination: ${apiResponse.data?.pagination ? 'exists' : 'undefined'}`);
    
    return apiResponse;
    
  } catch (error) {
    console.error('❌ API logic test failed:', error);
    return {
      success: false,
      error: error.message
    };
  }
}

async function runAllTests() {
  console.log('🔍 Starting API debugging tests...\n');
  
  // Test 1: Database connection and data
  const dbTest = await testDatabaseConnection();
  
  // Test 2: API logic simulation
  const apiTest = await testAPILogic();
  
  console.log('\n📋 Test Summary:');
  console.log(`Database connection: ${dbTest.success ? '✅ PASS' : '❌ FAIL'}`);
  console.log(`API logic simulation: ${apiTest.success ? '✅ PASS' : '❌ FAIL'}`);
  
  if (!dbTest.success || !apiTest.success) {
    console.log('\n🔧 Recommended actions:');
    if (!dbTest.success) {
      console.log('  - Check database connection string');
      console.log('  - Ensure database server is running');
      console.log('  - Run database migrations');
    }
    if (!apiTest.success) {
      console.log('  - Check API endpoint implementation');
      console.log('  - Verify Prisma client setup');
    }
  }
  
  return { dbTest, apiTest };
}

// Run the tests
if (require.main === module) {
  runAllTests()
    .then(() => {
      console.log('\n✅ Debugging tests completed!');
      process.exit(0);
    })
    .catch((error) => {
      console.error('\n❌ Debugging tests failed:', error);
      process.exit(1);
    });
}

module.exports = runAllTests; 