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";
import { accessLevelFor, parseScopes } from "@/lib/developers/scopes";
import { updateTokenScopes } from "@/lib/developers/token-store";

// PATCH { scopes }: change the per-section rights of a token. Only the person who created the token,
// only with a login session (never via API token) – finances/vault always belong to the token's creator.
export async function PATCH(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;
    let body: { scopes?: unknown } = {};
    try {
      body = await req.json();
    } catch {
      return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
    }
    const parsed = parseScopes(body.scopes);
    if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 });

    const { rows } = await sql`
      SELECT id, user_id, revoked_at FROM developer_api_tokens WHERE id = ${id}
    `;
    const token = rows[0];
    if (!token || token.user_id !== user.id) {
      return NextResponse.json({ error: "Token not found (only its creator can change rights)" }, { status: 404 });
    }
    if (token.revoked_at) {
      return NextResponse.json({ error: "Token is revoked" }, { status: 400 });
    }

    try {
      const updated = await updateTokenScopes(id, user.id, parsed.value, accessLevelFor(parsed.value));
      return NextResponse.json({ token: updated });
    } catch (error) {
      if ((error as { code?: string }).code === "42703") {
        return NextResponse.json({ error: "Per-section rights are not available yet (database migration missing)." }, { status: 409 });
      }
      throw error;
    }
  } catch (error) {
    logApiError("Developer token PATCH error", error);
    return NextResponse.json({ error: "Failed to update token rights" }, { status: 500 });
  }
}

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 });
  }
}
