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,
  generateDeveloperToken,
  getTokenPrefix,
  hashDeveloperToken,
  maskTokenPrefix,
} from "@/lib/developers/auth";

export async function GET(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

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

    const url = new URL(req.url);
    const teamId = url.searchParams.get("teamId");
    const manageable = await canManageWorkspace(user.id, teamId);

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

    const { rows } = teamId
      ? await sql`
          SELECT id, user_id, team_id, name, access_level, token_prefix, last_used_at, expires_at, revoked_at, created_at, updated_at
          FROM developer_api_tokens
          WHERE team_id = ${teamId}
          ORDER BY created_at DESC
        `
      : await sql`
          SELECT id, user_id, team_id, name, access_level, token_prefix, last_used_at, expires_at, revoked_at, created_at, updated_at
          FROM developer_api_tokens
          WHERE team_id IS NULL AND user_id = ${user.id}
          ORDER BY created_at DESC
        `;

    return NextResponse.json({ tokens: rows });
  } catch (error) {
    logApiError("Developer tokens GET error", error);
    return NextResponse.json({ error: "Failed to load API tokens" }, { status: 500 });
  }
}

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

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

    const body = await req.json();
    const teamId = typeof body.teamId === "string" && body.teamId ? body.teamId : null;
    const manageable = await canManageWorkspace(user.id, teamId);

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

    const token = generateDeveloperToken();
    const tokenHash = hashDeveloperToken(token);
    const tokenPrefix = getTokenPrefix(token);
    const name = String(body.name || "Developer token").trim() || "Developer token";
    const accessLevel = body.accessLevel === "read_only" ? "read_only" : "read_write";
    const expiresAt =
      typeof body.expiresAt === "string" && body.expiresAt ? body.expiresAt : null;

    const { rows } = await sql`
      INSERT INTO developer_api_tokens
        (user_id, team_id, name, access_level, token_prefix, token_hash, expires_at)
      VALUES
        (${user.id}, ${teamId}, ${name}, ${accessLevel}, ${tokenPrefix}, ${tokenHash}, ${expiresAt})
      RETURNING id, user_id, team_id, name, access_level, token_prefix, last_used_at, expires_at, revoked_at, created_at, updated_at
    `;

    if (!rows[0]) {
      return NextResponse.json({ error: "Failed to create API token" }, { status: 400 });
    }

    return NextResponse.json({
      token: rows[0],
      tokenValue: token,
      tokenHint: maskTokenPrefix(tokenPrefix),
    });
  } catch (error) {
    logApiError("Developer token POST error", error);
    return NextResponse.json({ error: "Failed to create API token" }, { status: 500 });
  }
}
