import { NextRequest, NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';
import { db } from '@/db';
import { clients } from '@/db/schema';

export async function GET(request: NextRequest) {
  const secret = process.env.INTERNAL_SECRET;
  // When secret is configured, enforce it. When unset, allow (route is localhost-only by design).
  if (secret && request.headers.get("x-internal-secret") !== secret) {
    return NextResponse.json({ valid: false }, { status: 403 });
  }

  const token = request.nextUrl.searchParams.get('token');

  if (!token) {
    return NextResponse.json({ valid: false }, { status: 400 });
  }

  try {
    const rows = await db
      .select({ id: clients.id })
      .from(clients)
      .where(eq(clients.token, token))
      .limit(1);

    if (rows.length === 0) {
      return NextResponse.json({ valid: false }, { status: 404 });
    }

    return NextResponse.json({ valid: true }, { status: 200 });
  } catch {
    return NextResponse.json({ valid: false }, { status: 500 });
  }
}