import { checkSquareConnection, getSquareLocationId, resetSquareClient } from "@/lib/square-client"

export async function GET(request: Request) {
  try {
    console.log("=== Square Health Check ===")
    
    // Reset client to force fresh initialization
    const { searchParams } = new URL(request.url)
    if (searchParams.get('reset') === 'true') {
      resetSquareClient()
      console.log("Square client reset")
    }
    
    // Check environment variables
    const envCheck = {
      SQUARE_ACCESS_TOKEN: {
        exists: !!process.env.SQUARE_ACCESS_TOKEN,
        length: process.env.SQUARE_ACCESS_TOKEN?.length || 0,
        startsWithEAAA: process.env.SQUARE_ACCESS_TOKEN?.startsWith("EAAA") || false,
      },
      SQUARE_LOCATION_ID: {
        exists: !!process.env.SQUARE_LOCATION_ID,
        length: process.env.SQUARE_LOCATION_ID?.length || 0,
        startsWithL: process.env.SQUARE_LOCATION_ID?.startsWith("L") || false,
      },
      SQUARE_ENVIRONMENT: {
        exists: !!process.env.SQUARE_ENVIRONMENT,
        value: process.env.SQUARE_ENVIRONMENT || "not set",
        isValid: ["sandbox", "production"].includes(process.env.SQUARE_ENVIRONMENT || ""),
      },
      NODE_ENV: process.env.NODE_ENV,
    }

    console.log("Environment check:", envCheck)

    // Test Square connection
    const connectionResult = await checkSquareConnection()
    console.log("Connection result:", connectionResult)

    return Response.json({
      success: connectionResult.success,
      environment: envCheck,
      connection: connectionResult,
      timestamp: new Date().toISOString(),
      recommendations: {
        accessToken: !envCheck.SQUARE_ACCESS_TOKEN.exists
          ? "❌ Missing SQUARE_ACCESS_TOKEN"
          : !envCheck.SQUARE_ACCESS_TOKEN.startsWithEAAA
            ? "⚠️ Token should start with 'EAAA'"
            : "✅ Access token looks good",
        locationId: !envCheck.SQUARE_LOCATION_ID.exists
          ? "❌ Missing SQUARE_LOCATION_ID"
          : !envCheck.SQUARE_LOCATION_ID.startsWithL
            ? "⚠️ Location ID should start with 'L'"
            : "✅ Location ID looks good",
        environment: !envCheck.SQUARE_ENVIRONMENT.isValid
          ? "⚠️ Should be 'sandbox' or 'production'"
          : "✅ Environment is valid",
        sdkImport: connectionResult.success 
          ? "✅ Square SDK imported successfully"
          : "❌ Square SDK import failed - check if 'squareup' package is installed"
      }
    })

  } catch (error) {
    console.error("Health check failed:", error)
    
    return Response.json({
      success: false,
      error: error instanceof Error ? error.message : "Health check failed",
      timestamp: new Date().toISOString(),
      details: {
        type: error?.constructor?.name || "Unknown",
        message: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined
      }
    }, { status: 500 })
  }
}
