import { NextRequest, NextResponse } from "next/server";
import {
  listApiTokens,
  createApiToken,
  generateToken,
} from "@/lib/api-token";
import { createAuditLog } from "@/lib/log";

export async function GET(req: NextRequest) {
  try {
    const tokens = await listApiTokens();
    return NextResponse.json({ tokens });
  } catch (e) {
    console.error("List tokens error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json() as {
      name?: string;
      permissions?: string[];
      expiresInDays?: number;
    };
    const { name = "", permissions = [], expiresInDays } = body;

    if (!name.trim()) {
      return NextResponse.json({ error: "Token 名称不能为空" }, { status: 400 });
    }

    const token = generateToken();
    const expiresAt = expiresInDays
      ? new Date(Date.now() + expiresInDays * 86400 * 1000)
      : null;

    const adminUserId = parseInt(req.headers.get("x-admin-user-id") || "0", 10);
    const adminUsername = req.headers.get("x-admin-username") || "unknown";

    const result = await createApiToken({
      name: name.trim(),
      token,
      permissions,
      createdBy: adminUserId,
      expiresAt,
    });

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "create",
      resource: "admin_api_token",
      resourceId: String(result.id),
      requestParams: { name: name.trim(), permissions, expiresInDays },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ id: result.id, token, name: name.trim(), expiresAt }, { status: 201 });
  } catch (e) {
    console.error("Create token error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
