import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
  const hasApiUrl = !!process.env.AUTOTASK_API_URL;
  const hasUsername = !!process.env.AUTOTASK_USERNAME;
  const hasPassword = !!process.env.AUTOTASK_SECRET;
  const hasIntegrationCode = !!process.env.AUTOTASK_API_INTEGRATION_CODE;

  const configStatus = {
    apiUrl: hasApiUrl ? 'configured' : 'missing',
    username: hasUsername ? 'configured' : 'missing',
    password: hasPassword ? 'configured' : 'missing',
    integrationCode: hasIntegrationCode ? 'configured' : 'missing',
  };

  const isConfigured = hasApiUrl && hasUsername && hasPassword && hasIntegrationCode;

  if (!isConfigured) {
    return NextResponse.json(
      {
        status: 'error',
        message: 'Autotask API is not properly configured',
        configuration: configStatus,
        instructions: [
          '1. Create a .env.local file in the root directory',
          '2. Add the following environment variables:',
          '   - AUTOTASK_API_URL',
          '   - AUTOTASK_USERNAME',
          '   - AUTOTASK_SECRET',
          '   - AUTOTASK_API_INTEGRATION_CODE',
          '3. Restart the development server',
          '',
          'See .env.local.example for a template'
        ]
      },
      { status: 503 }
    );
  }

  // Try to make a test API call
  try {
    const { getAutotaskClient } = await import('@/lib/services/autotask-factory');
    const client = getAutotaskClient();
    
    // Test with a simple API call - get entity info
    const testUrl = `${process.env.AUTOTASK_API_URL}/Tickets/entityInformation`;

    const response = await fetch(testUrl, {
      method: 'GET',
      headers: {
        'Username': process.env.AUTOTASK_USERNAME || '',
        'Secret': process.env.AUTOTASK_SECRET || '',
        'APIIntegrationcode': process.env.AUTOTASK_API_INTEGRATION_CODE || '',
        'Content-Type': 'application/json',
        'Accept': 'application/json',
      },
    });

    if (response.ok) {
      return NextResponse.json({
        status: 'healthy',
        message: 'Autotask API connection successful',
        configuration: configStatus,
        apiUrl: process.env.AUTOTASK_API_URL,
      });
    } else {
      const errorText = await response.text();
      return NextResponse.json(
        {
          status: 'error',
          message: 'Autotask API connection failed',
          configuration: configStatus,
          apiResponse: {
            status: response.status,
            statusText: response.statusText,
            error: errorText
          },
          possibleIssues: [
            'Invalid API credentials',
            'Incorrect API URL or zone',
            'API user lacks permissions',
            'Integration code is invalid'
          ]
        },
        { status: 503 }
      );
    }
  } catch (error) {
    return NextResponse.json(
      {
        status: 'error',
        message: 'Failed to connect to Autotask API',
        configuration: configStatus,
        error: error instanceof Error ? error.message : 'Unknown error',
        possibleIssues: [
          'Network connectivity issues',
          'Invalid API URL format',
          'Server configuration error'
        ]
      },
      { status: 503 }
    );
  }
}
