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

const AUTOTASK_ZONES = [
  'https://webservices1.autotask.net/atservicesrest/v1.0',
  'https://webservices2.autotask.net/atservicesrest/v1.0',
  'https://webservices3.autotask.net/atservicesrest/v1.0',
  'https://webservices4.autotask.net/atservicesrest/v1.0',
  'https://webservices5.autotask.net/atservicesrest/v1.0',
  'https://webservices6.autotask.net/atservicesrest/v1.0',
  'https://prde.autotask.net/atservicesrest/v1.0',
  'https://ioce.autotask.net/atservicesrest/v1.0',
];

export async function GET(request: NextRequest) {
  const username = process.env.AUTOTASK_USERNAME;
  const password = process.env.AUTOTASK_SECRET;
  const integrationCode = process.env.AUTOTASK_API_INTEGRATION_CODE;

  if (!username || !password || !integrationCode) {
    return NextResponse.json({
      error: 'Missing credentials in environment variables'
    }, { status: 400 });
  }

  const headers = {
    'Username': username,
    'Secret': password,
    'APIIntegrationcode': integrationCode,
    'Content-Type': 'application/json',
    'Accept': 'application/json',
  };

  const results = [];

  for (const zoneUrl of AUTOTASK_ZONES) {
    const zoneName = zoneUrl.match(/\/\/(.*?)\./)?.[1] || 'unknown';
    
    try {
      const response = await fetch(`${zoneUrl}/Tickets/entityInformation`, {
        method: 'GET',
        headers,
      });

      if (response.ok) {
        results.push({
          zone: zoneName,
          url: zoneUrl,
          status: 'SUCCESS',
          statusCode: response.status,
          message: 'Connection successful! This is your correct zone.'
        });
        
        // If we found the correct zone, return immediately
        return NextResponse.json({
          success: true,
          correctZone: {
            zone: zoneName,
            url: zoneUrl,
          },
          message: `Found your Autotask zone: ${zoneName}`,
          instruction: `Update your .env.local file with: AUTOTASK_API_URL=${zoneUrl}`
        });
      } else {
        results.push({
          zone: zoneName,
          url: zoneUrl,
          status: 'FAILED',
          statusCode: response.status,
          message: response.statusText
        });
      }
    } catch (error) {
      results.push({
        zone: zoneName,
        url: zoneUrl,
        status: 'ERROR',
        message: error instanceof Error ? error.message : 'Connection failed'
      });
    }
  }

  // If no zone worked
  return NextResponse.json({
    success: false,
    message: 'Could not find the correct Autotask zone',
    testedZones: results,
    possibleIssues: [
      'Invalid username or password',
      'Invalid integration code',
      'API user account is disabled',
      'Your zone might not be in the standard list'
    ]
  }, { status: 404 });
}
