import { NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import OpenAI from 'openai';
import { RowDataPacket } from 'mysql2';

// Initialize DeepSeek
const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  baseURL: 'https://api.deepseek.com/v1'
});

// System prompt optimized for your exact use case
const SYSTEM_PROMPT = `You are an expert university course eligibility analyzer. 
Your task is to analyze student profiles against specific courses and provide eligibility analysis.

You receive:
1. Student profile: {country, qualification, GPA, budget, English test, major}
2. Course details: {university, course name, fees, requirements, etc.}

ANALYSIS CRITERIA (based on provided data only):
1. Academic Fit (30%): GPA vs required GPA, qualification match
2. Financial Fit (25%): Budget vs course fees, scholarship availability
3. Country/University Fit (20%): Country preference, university reputation
4. Requirements Match (15%): English test requirements
5. Major Alignment (10%): Course subject relevance to student's major interest

RESPONSE RULES:
- ONLY use the data provided, do not invent new fields
- Provide numerical scores (0-100) for each criterion
- Give specific, actionable insights in plain English
- Highlight exact mismatches (e.g., "GPA is 0.2 below requirement")
- Suggest concrete alternatives when possible
- Be realistic and data-driven
- Format all text in clean, readable format (no markdown, no **, no ##, no bold)`;

// Maximum courses to analyze
const MAX_COURSES_TO_ANALYZE = 32;

// Batch size for AI analysis (to avoid rate limiting)
const AI_BATCH_SIZE = 8;
const AI_DELAY_BETWEEN_BATCHES = 100; // ms between batches

// Function to delay execution
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));

export async function POST(request) {
  const connection = await pool.getConnection();
  
  try {
    const body = await request.json();
    
    // EXACT SAME FIELDS as original
    const { 
      country = '', 
      qualification = '', 
      max_fee = 0, 
      gpa = 0, 
      english_test_type = '', 
      english_test_score = 0, 
      limit = MAX_COURSES_TO_ANALYZE, // Always get 32 courses
      major = '', 
      page = 1 
    } = body;

    // Parse values exactly as original
    const safeLimit = Math.min(parseInt(limit) || MAX_COURSES_TO_ANALYZE, MAX_COURSES_TO_ANALYZE);
    const safePage = 1; // Always get first page for 32 courses
    const offset = (safePage - 1) * safeLimit;
    const maxFeeNum = parseFloat(max_fee) || 0;
    const userGPA = parseFloat(gpa) || 0;
    const userEnglishScore = parseFloat(english_test_score) || 0;

    // =================== STEP 0: GET QUALIFICATION AND MAJOR NAMES ===================
    
    let qualificationName = 'Not specified';
    let majorName = 'Not specified';
    
    // Get qualification name from posts table
    if (qualification && qualification !== '') {
      try {
        const [qualRows] = await connection.query<RowDataPacket[]>(
          'SELECT title FROM posts WHERE ID = ? LIMIT 1',
          [qualification]
        );
        if (qualRows.length > 0 && qualRows[0].title) {
          qualificationName = qualRows[0].title;
        }
      } catch (error) {
        console.error('Error fetching qualification name:', error);
      }
    }
    
    // Get major name from subjects table
    if (major && major !== '') {
      try {
        const [majorRows] = await connection.query<RowDataPacket[]>(
          'SELECT name FROM subjects WHERE id = ? LIMIT 1',
          [major]
        );
        if (majorRows.length > 0 && majorRows[0].name) {
          majorName = majorRows[0].name;
        }
      } catch (error) {
        console.error('Error fetching major name:', error);
      }
    }

    // =================== STEP 1: INTELLIGENT FILTERING WITH SCORING ===================
    
    // Build base query with intelligent match scoring
    let sqlQuery = `
      SELECT 
        c.id,
        c.name,
        c.qualification,
        c.yearly_fee,
        c.duration,
        c.scholarship,
        c.deadline,
        c.created_at,
        u.name as university_name,
        u.ranking,
        u.cgpa as required_cgpa,
        u.english_test_requirements,
        u.acceptance_rate,
        u.website,
        u.country,
        u.university_type,
        co.country as country_name,
        co.currency_symbol,
        co.currency as currency_code,
        s.name as subject_name,
        s.id as subject_id,
        -- Get qualification name from posts table
        (SELECT title FROM posts WHERE ID = c.qualification LIMIT 1) as qualification_name,
        -- Calculate initial match score (0-100)
        (
          -- 1. Country Match (30 points max)
          CASE 
            WHEN ? = '' THEN 15  -- No country preference = neutral score
            WHEN co.country = ? THEN 30  -- Exact country match
            ELSE 0
          END +
          
          -- 2. Qualification Match (25 points max)
          CASE 
            WHEN ? = '' THEN 12  -- No qualification preference
            WHEN c.qualification = ? THEN 25  -- Exact qualification match
            ELSE 0
          END +
          
          -- 3. Major/Subject Match (20 points max)
          CASE 
            WHEN ? = '' THEN 10  -- No major preference
            WHEN c.subject_id = ? THEN 20  -- Exact subject match
            ELSE 0
          END +
          
          -- 4. Financial Fit (15 points max)
          CASE 
            WHEN ? = 0 THEN 7  -- No budget constraint
            WHEN c.yearly_fee <= ? THEN 15  -- Within budget
            WHEN c.yearly_fee <= ? * 1.3 THEN 10  -- Slightly over budget (within 30%)
            WHEN c.yearly_fee <= ? * 1.5 THEN 5  -- Moderately over budget (within 50%)
            ELSE 0  -- Too expensive
          END +
          
          -- 5. GPA Match (10 points max)
          CASE 
            WHEN u.cgpa IS NULL THEN 5  -- No GPA requirement = neutral
            WHEN ? >= u.cgpa THEN 10  -- Meets or exceeds requirement
            WHEN ? >= u.cgpa * 0.9 THEN 7  -- Close to requirement (within 10%)
            WHEN ? >= u.cgpa * 0.8 THEN 3  -- Somewhat close (within 20%)
            ELSE 0  -- Below requirement
          END
        ) as match_score
      FROM courses c
      JOIN university_details u ON c.university_id = u.id
      JOIN countries co ON u.country = co.country
      LEFT JOIN subjects s ON c.subject_id = s.id
      WHERE 1=1
    `;

    // Build where conditions for filtering (not just scoring)
    let whereConditions = '';
    const queryParams = [
      // For scoring parameters
      country, country,
      qualification, qualification,
      major, major,
      maxFeeNum, maxFeeNum, maxFeeNum, maxFeeNum,
      userGPA, userGPA, userGPA
    ];

    // Apply actual filters (strict matching for better results)
    if (country && country !== '') {
      whereConditions += ` AND co.country = ?`;
      queryParams.push(country);
    }

    if (qualification && qualification !== '') {
      whereConditions += ` AND c.qualification = ?`;
      queryParams.push(qualification);
    }

    if (major && major !== '') {
      whereConditions += ` AND c.subject_id = ?`;
      queryParams.push(major);
    }

    // Filter by budget if specified
    if (maxFeeNum > 0) {
      // Show courses within 50% of budget OR with scholarships
      whereConditions += ` AND (c.yearly_fee <= ? * 1.5 OR c.scholarship = 1)`;
      queryParams.push(maxFeeNum);
    }

    // Filter by GPA if specified and has requirements
    if (userGPA > 0) {
      // Show courses where user meets GPA OR no GPA requirement OR close to requirement
      whereConditions += ` AND (u.cgpa IS NULL OR ? >= u.cgpa * 0.7)`;
      queryParams.push(userGPA);
    }

    // Complete the query with ordering by match score
    sqlQuery += whereConditions + ` 
      ORDER BY 
        match_score DESC,
        -- Secondary sort: higher ranking universities first
        CASE WHEN u.ranking IS NOT NULL THEN 1 ELSE 2 END,
        u.ranking ASC,
        -- Tertiary sort: newer courses first
        c.created_at DESC
      LIMIT ? OFFSET ?`;

    // Add limit and offset parameters
    queryParams.push(safeLimit, offset);

    // Execute the query
    const [courses] = await connection.query<RowDataPacket[]>(sqlQuery, queryParams);

    if (courses.length === 0) {
      return NextResponse.json({
        success: false,
        courses: [],
        message: "No courses found matching your criteria. Try adjusting your preferences."
      });
    }

    // =================== STEP 2: PREPARE USER PROFILE FOR AI ===================
    const userProfile = {
      country: country || "Not specified",
      qualification: qualificationName,
      gpa: userGPA,
      budget: maxFeeNum,
      english_test: {
        type: english_test_type || "none",
        score: userEnglishScore
      },
      major_interest: majorName
    };

    // =================== STEP 3: AI ANALYSIS FOR ALL 32 COURSES (IN BATCHES) ===================
    const analyzedCourses = [];
    
    // Process courses in batches to avoid rate limiting
    for (let i = 0; i < courses.length; i += AI_BATCH_SIZE) {
      const batch = courses.slice(i, i + AI_BATCH_SIZE);
      const batchPromises = batch.map(async (course) => {
        // Parse English requirements safely
        let englishRequirements = [];
        try {
          if (course.english_test_requirements) {
            englishRequirements = JSON.parse(course.english_test_requirements);
          }
        } catch (e) {
          // Keep empty array if parsing fails
        }

        // Format course details for AI
        const courseQualificationName = course.qualification_name || course.qualification || 'Not specified';
        const courseSubjectName = course.subject_name || 'General';
        const courseRanking = course.ranking ? `Rank: ${course.ranking}` : 'Ranking not available';
        const courseLocation = course.location ? `(${course.location})` : '';
        const courseType = course.university_type ? `Type: ${course.university_type}` : '';

        // Create AI prompt with enhanced context including meaningful names
        const prompt = `
        Analyze eligibility for this student considering EXACTLY these factors:

        STUDENT PROFILE (use only this data):
        - Desired Country: ${userProfile.country}
        - Desired Qualification: ${userProfile.qualification}
        - Current GPA: ${userProfile.gpa}
        - Maximum Budget: ${userProfile.budget} ${course.currency_symbol}
        - English Test: ${userProfile.english_test.type} (Score: ${userProfile.english_test.score})
        - Major Interest: ${userProfile.major_interest}

        COURSE DETAILS:
        - Course: ${course.name}
        - University: ${course.university_name}
        - Location: ${course.country_name} ${courseLocation}
        - University Info: ${courseRanking}, ${courseType}
        - Required GPA: ${course.required_cgpa || 'Not specified'}
        - Annual Fee: ${course.yearly_fee} ${course.currency_symbol}
        - Scholarship Available: ${course.scholarship ? 'Yes' : 'No'}
        - English Requirements: ${JSON.stringify(englishRequirements)}
        - Course Qualification: ${courseQualificationName}
        - Subject Area: ${courseSubjectName}
        - Acceptance Rate: ${course.acceptance_rate || 'Unknown'}%
        - Admission Deadline: ${course.deadline || 'Rolling'}
        - Initial Match Score: ${course.match_score}/100 (pre-filtered relevance)

        Provide analysis in this EXACT JSON format:
        {
          "eligibility_score": number (0-100),
          "score_breakdown": {
            "academic_fit": number (0-100),
            "financial_fit": number (0-100),
            "country_university_fit": number (0-100),
            "requirements_match": number (0-100),
            "major_alignment": number (0-100)
          },
          "analysis_summary": "2-3 sentence summary in plain English",
          "key_strengths": ["array", "of", "strengths"],
          "key_concerns": ["array", "of", "concerns"],
          "recommendation": "strong_recommend|recommend_with_conditions|not_recommended",
          "specific_advice": "Specific actionable advice for this student-course pair in plain English",
          "improvement_suggestions": ["suggestion1", "suggestion2"]
        }

        IMPORTANT FORMATTING RULES:
        1. ALL text must be in plain English format (NO markdown, NO **, NO ##, NO bold, NO italics)
        2. Use only plain text, simple sentences
        3. Base analysis ONLY on provided data
        4. Consider the initial match score in your evaluation
        5. Be realistic about gaps
        6. If data is missing, note it as a limitation
        7. Prioritize objective criteria over subjective opinions
        `;

        try {
          const response = await deepseek.chat.completions.create({
            model: "deepseek-chat",
            messages: [
              { 
                role: "system", 
                content: SYSTEM_PROMPT + "\n\nFORMATTING INSTRUCTIONS: Respond with clean, readable text only. No markdown formatting, no **, no ##, no bold, no italics. Use plain English sentences." 
              },
              { role: "user", content: prompt }
            ],
            temperature: 0.2,
            max_tokens: 800,
            response_format: { type: "json_object" }
          });

          let aiAnalysis;
          try {
            aiAnalysis = JSON.parse(response.choices[0].message.content);
            
            // Clean any markdown formatting from AI response
            const cleanText = (text) => {
              if (!text) return text;
              return text
                .replace(/\*\*(.*?)\*\*/g, '$1')  // Remove **bold**
                .replace(/\*(.*?)\*/g, '$1')      // Remove *italics*
                .replace(/#+\s*/g, '')            // Remove # headings
                .replace(/`(.*?)`/g, '$1')        // Remove `code`
                .replace(/\[(.*?)\]\(.*?\)/g, '$1') // Remove [links](url)
                .replace(/\n{3,}/g, '\n\n')       // Replace 3+ newlines with 2
                .trim();
            };

            // Clean all text fields in the AI response
            if (aiAnalysis.analysis_summary) {
              aiAnalysis.analysis_summary = cleanText(aiAnalysis.analysis_summary);
            }
            if (aiAnalysis.specific_advice) {
              aiAnalysis.specific_advice = cleanText(aiAnalysis.specific_advice);
            }
            if (aiAnalysis.key_strengths) {
              aiAnalysis.key_strengths = aiAnalysis.key_strengths.map(cleanText);
            }
            if (aiAnalysis.key_concerns) {
              aiAnalysis.key_concerns = aiAnalysis.key_concerns.map(cleanText);
            }
            if (aiAnalysis.improvement_suggestions) {
              aiAnalysis.improvement_suggestions = aiAnalysis.improvement_suggestions.map(cleanText);
            }

          } catch (parseError) {
            console.error('Failed to parse AI response:', parseError);
            aiAnalysis = {
              eligibility_score: course.match_score || 50,
              score_breakdown: {
                academic_fit: 50,
                financial_fit: 50,
                country_university_fit: 50,
                requirements_match: 50,
                major_alignment: 50
              },
              analysis_summary: "AI analysis unavailable. Course details are available for review.",
              key_strengths: ["Course meets basic filtering criteria"],
              key_concerns: ["Detailed AI analysis could not be generated"],
              recommendation: "recommend_with_conditions",
              specific_advice: "Please review course details manually and contact the university for specific requirements.",
              improvement_suggestions: ["Verify requirements directly with university", "Consider alternative programs"]
            };
          }

          // Combine AI analysis with course data
          return {
            // Original course data
            id: course.id,
            name: course.name,
            university_name: course.university_name,
            country_name: course.country_name,
            yearly_fee: course.yearly_fee?.toString() || '0',
            duration: course.duration?.toString() || '12',
            scholarship: Boolean(course.scholarship),
            currency_symbol: course.currency_symbol,
            website: course.website,
            admission_deadline: course.deadline,
            required_cgpa: course.required_cgpa,
            acceptance_rate: course.acceptance_rate,
            location: course.location,
            ranking: course.ranking,
            university_type: course.university_type,
            qualification_name: courseQualificationName,
            subject_name: courseSubjectName,
            
            // AI Analysis
            ai_analysis: {
              ...aiAnalysis,
              // Add computed fields for easier frontend use
              is_highly_eligible: aiAnalysis.eligibility_score >= 80,
              is_moderately_eligible: aiAnalysis.eligibility_score >= 60 && aiAnalysis.eligibility_score < 80,
              is_low_eligible: aiAnalysis.eligibility_score < 60,
              analysis_timestamp: new Date().toISOString(),
              initial_match_score: course.match_score || 0
            },

            // Compatibility with existing frontend
            similarity_score: Math.min(100, aiAnalysis.eligibility_score),
            eligibility: {
              status: aiAnalysis.eligibility_score >= 80 ? 'high' : 
                      aiAnalysis.eligibility_score >= 60 ? 'medium' : 'low',
              message: aiAnalysis.analysis_summary,
              cgpa_met: aiAnalysis.score_breakdown.academic_fit >= 70,
              english_test_met: aiAnalysis.score_breakdown.requirements_match >= 70,
              minimum_cgpa: course.required_cgpa,
              english_requirements: englishRequirements
            }
          };

        } catch (error) {
          console.error(`AI analysis failed for course ${course.id}:`, error);
          
          // Fallback: Return course without AI analysis but with match score
          return {
            ...course,
            yearly_fee: course.yearly_fee?.toString() || '0',
            duration: course.duration?.toString() || '12',
            scholarship: Boolean(course.scholarship),
            qualification_name: courseQualificationName,
            subject_name: courseSubjectName,
            ai_analysis: {
              error: "AI analysis unavailable",
              fallback_message: "Course details available, but AI analysis failed",
              eligibility_score: course.match_score || 50,
              initial_match_score: course.match_score || 0,
              analysis_summary: "Manual review recommended. Please check course details carefully."
            },
            similarity_score: course.match_score || 50,
            eligibility: {
              status: 'medium',
              message: 'Manual review recommended',
              cgpa_met: userGPA >= (course.required_cgpa || 0),
              english_test_met: false,
              minimum_cgpa: course.required_cgpa,
              english_requirements: englishRequirements
            }
          };
        }
      });

      // Process this batch
      const batchResults = await Promise.all(batchPromises);
      analyzedCourses.push(...batchResults);
      
      // Add delay between batches to avoid rate limiting (if not the last batch)
      if (i + AI_BATCH_SIZE < courses.length) {
        await delay(AI_DELAY_BETWEEN_BATCHES);
      }
    }

    // =================== STEP 4: GET TOTAL COUNT FOR INFORMATION ===================
    // Build count query with same filters
    let countQuery = `
      SELECT COUNT(*) as total 
      FROM courses c
      JOIN university_details u ON c.university_id = u.id
      JOIN countries co ON u.country = co.country
      LEFT JOIN subjects s ON c.subject_id = s.id
      WHERE 1=1
    `;
    
    const countParams = [];
    
    if (country && country !== '') {
      countQuery += ` AND co.country = ?`;
      countParams.push(country);
    }

    if (qualification && qualification !== '') {
      countQuery += ` AND c.qualification = ?`;
      countParams.push(qualification);
    }

    if (major && major !== '') {
      countQuery += ` AND c.subject_id = ?`;
      countParams.push(major);
    }

    if (maxFeeNum > 0) {
      countQuery += ` AND (c.yearly_fee <= ? * 1.5 OR c.scholarship = 1)`;
      countParams.push(maxFeeNum);
    }

    if (userGPA > 0) {
      countQuery += ` AND (u.cgpa IS NULL OR ? >= u.cgpa * 0.7)`;
      countParams.push(userGPA);
    }

    const [totalRows] = await connection.query<RowDataPacket[]>(countQuery, countParams);
    const total = totalRows[0]?.total || 0;

    // =================== STEP 5: GENERATE OVERALL PROFILE SUMMARY ===================
    let overallSummary = null;
    if (analyzedCourses.length > 0) {
      try {
        // Calculate average match score
        const validScores = analyzedCourses
          .filter(course => course.ai_analysis?.eligibility_score)
          .map(course => course.ai_analysis.eligibility_score);
        
        const avgScore = validScores.length > 0 
          ? validScores.reduce((a, b) => a + b, 0) / validScores.length 
          : 50;

        const highMatchCount = analyzedCourses.filter(c => 
          (c.ai_analysis?.eligibility_score || c.similarity_score || 0) >= 80
        ).length;

        const summaryPrompt = `
        Based on ${analyzedCourses.length} AI-analyzed courses for this student:

        STUDENT PROFILE:
        - Desired Study Country: ${userProfile.country}
        - Desired Qualification Level: ${userProfile.qualification}
        - Current Academic GPA: ${userProfile.gpa}
        - Available Budget: ${userProfile.budget} (${courses[0]?.currency_symbol || '$'})
        - English Language Proficiency: ${userProfile.english_test.type} Score: ${userProfile.english_test.score}
        - Field of Interest: ${userProfile.major_interest}

        ANALYSIS CONTEXT:
        - Total Courses Analyzed: ${analyzedCourses.length}
        - Average AI Eligibility Score: ${avgScore.toFixed(1)}/100
        - Highly Recommended Courses: ${highMatchCount}
        - Country Filter: ${country || 'All countries considered'}
        - Budget Constraint: ${maxFeeNum > 0 ? `${maxFeeNum} ${courses[0]?.currency_symbol || '$'}` : 'Flexible budget'}

        Provide a concise overall summary in PLAIN ENGLISH (no markdown, no formatting):
        1. Brief assessment of overall competitiveness
        2. Main strengths based on the analysis
        3. Key areas for improvement or consideration
        4. General recommendation for next steps

        Keep it professional, encouraging, and realistic. Maximum 150 words.
        `;

        const summaryResponse = await deepseek.chat.completions.create({
          model: "deepseek-chat",
          messages: [
            { 
              role: "system", 
              content: "You are an educational consultant providing concise, actionable summaries in clean plain English. No markdown formatting, no **, no ##, no bold, no italics. Use only plain text with proper sentences." 
            },
            { role: "user", content: summaryPrompt }
          ],
          temperature: 0.3,
          max_tokens: 300
        });

        // Clean the summary text
        let summaryText = summaryResponse.choices[0].message.content;
        summaryText = summaryText
          .replace(/\*\*(.*?)\*\*/g, '$1')
          .replace(/\*(.*?)\*/g, '$1')
          .replace(/#+\s*/g, '')
          .replace(/`(.*?)`/g, '$1')
          .replace(/\[(.*?)\]\(.*?\)/g, '$1')
          .replace(/\n{3,}/g, '\n\n')
          .trim();

        overallSummary = summaryText;
      } catch (error) {
        console.error('Overall summary generation failed:', error);
        overallSummary = "Individual AI analyses are available below for each course. Review each program carefully based on your specific profile.";
      }
    }

    // =================== STEP 6: RETURN OPTIMIZED RESPONSE ===================
    // Sort analyzed courses by AI score (highest first)
    const sortedCourses = [...analyzedCourses].sort((a, b) => {
      const scoreA = a.ai_analysis?.eligibility_score || a.similarity_score || 0;
      const scoreB = b.ai_analysis?.eligibility_score || b.similarity_score || 0;
      return scoreB - scoreA; // Descending order
    });

    return NextResponse.json({
      success: true,
      courses: sortedCourses,
      total_results: total,
      pagination: {
        current_page: safePage,
        total_pages: 1, // Only one page for client-side pagination
        has_next_page: false,
        has_prev_page: false,
        limit: safeLimit,
        showing_results: sortedCourses.length,
        total_courses_analyzed: sortedCourses.length,
        note: "All courses are pre-loaded for client-side pagination"
      },
      user_profile: {
        country: country,
        qualification: qualificationName,
        gpa: gpa,
        english_test_type: english_test_type,
        english_test_score: english_test_score,
        budget: max_fee,
        major: majorName,
        has_english_test: english_test_type && english_test_type !== 'none'
      },
      ai_insights: {
        overall_summary: overallSummary,
        analyzed_courses_count: sortedCourses.length,
        average_eligibility_score: sortedCourses.length > 0 
          ? Math.round(sortedCourses.reduce((sum, course) => 
              sum + (course.ai_analysis?.eligibility_score || course.similarity_score || 0), 0) / sortedCourses.length
            )
          : 0,
        highly_recommended_count: sortedCourses.filter(c => 
          (c.ai_analysis?.eligibility_score || c.similarity_score || 0) >= 80
        ).length,
        model_used: "deepseek-chat",
        note: "All 32 courses analyzed upfront for instant client-side pagination. Verify with official university sources."
      },
      meta: {
        timestamp: new Date().toISOString(),
        response_format: "ai_enhanced_32_courses",
        filtering_logic: "intelligent_match_scoring",
        batch_size: safeLimit,
        data_enrichment: "qualification_and_major_names_included",
        client_side_pagination: true,
        courses_per_page: 8,
        total_pages_client: Math.ceil(sortedCourses.length / 8)
      }
    });

  } catch (error) {
    console.error('AI Eligibility Calculator error:', error);
    
    // Fallback: Return error with suggestion to use regular calculator
    return NextResponse.json(
      { 
        success: false,
        error: 'AI analysis service temporarily unavailable',
        message: 'Please try the regular eligibility calculator or try again later',
        fallback_url: '/api/frontend/eligibility-calculator',
        debug: process.env.NODE_ENV === 'development' ? error.message : undefined
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}