import { NextRequest, NextResponse } from "next/server";
import { getServiceSupabase } from "@/lib/supabase/client";

export async function GET(req: NextRequest) {
  try {
    const supabase = getServiceSupabase();
    
    // Test database connection
    const { data: tasks, error } = await supabase
      .from("tasks")
      .select("count")
      .limit(1);
    
    if (error) {
      return NextResponse.json({ error: error.message, code: error.code }, { status: 500 });
    }
    
    // Check env vars
    const envCheck = {
      hasUrl: !!process.env.SUPABASE_URL || !!process.env.NEXT_PUBLIC_SUPABASE_URL,
      hasAnonKey: !!process.env.SUPABASE_ANON_KEY || !!process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY,
      hasServiceKey: !!process.env.SUPABASE_SERVICE_ROLE_KEY || !!process.env.SUPABASE_SECRET_KEY,
    };
    
    return NextResponse.json({ 
      success: true, 
      taskCount: tasks?.[0]?.count || 0,
      env: envCheck 
    });
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
