import { NextResponse } from "next/server";
import { logApiError } from "@/lib/api/security";
import { createRouteClient } from "@/lib/supabase/route";
import { sql } from "@/lib/db/postgres";
import { canManageWorkspace } from "@/lib/developers/auth";

export async function DELETE(
  _req: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id } = await context.params;
    const { rows } = await sql`
      SELECT id, team_id, user_id FROM developer_api_tokens WHERE id = ${id}
    `;
    const token = rows[0];

    if (!token) {
      return NextResponse.json({ error: "Token not found" }, { status: 404 });
    }

    const manageable =
      token.user_id === user.id ||
      (await canManageWorkspace(user.id, (token.team_id as string | null) || null));

    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    await sql`
      UPDATE developer_api_tokens SET revoked_at = ${new Date().toISOString()} WHERE id = ${id}
    `;

    return NextResponse.json({ success: true });
  } catch (error) {
    logApiError("Developer token DELETE error", error);
    return NextResponse.json({ error: "Failed to revoke API token" }, { status: 500 });
  }
}
