import { logError } from "@/lib/logger";
import { NextRequest, NextResponse } from "next/server";
import { query } from "@/lib/db";
import { createAuditLog } from "@/lib/log";
import argon2 from "argon2";

export const runtime = "nodejs";

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ uid: string }> }
) {
  try {
    const { uid } = await params;

    const result = await query(
      `SELECT u.uid, u.username, u.display_name, u.avatar_url,
              u.website_url, u.organization,
              u.last_sign_in_at::text, u.created_at::text,
              up.is_active,
              ue.email
       FROM "user" u
       LEFT JOIN user_password up ON up.user = u.uid
       LEFT JOIN user_email ue ON ue.user = u.uid
       WHERE u.uid = $1`,
      [uid]
    );

    if (!result.rows.length) {
      return NextResponse.json({ error: "用户不存在" }, { status: 404 });
    }

    const r = result.rows[0];
    return NextResponse.json({
      user: {
        uid: r.uid,
        username: r.username,
        displayName: r.display_name,
        avatarUrl: r.avatar_url,
        websiteUrl: r.website_url,
        organization: r.organization,
        lastSignInAt: r.last_sign_in_at,
        createdAt: r.created_at,
        isActive: r.is_active ?? true,
        email: r.email,
      },
    });
  } catch (e) {
    logError("Get user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}

export async function PATCH(
  req: NextRequest,
  { params }: { params: Promise<{ uid: string }> }
) {
  try {
    const { uid } = await params;
    const body = await req.json() as {
      email?: string;
      password?: string;
      displayName?: string;
      organization?: string;
    };

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

    // 检查用户是否存在
    const exist = await query<{ uid: string }>(`SELECT uid FROM "user" WHERE uid = $1`, [uid]);
    if (!exist.rows.length) {
      return NextResponse.json({ error: "用户不存在" }, { status: 404 });
    }

    // 修改邮箱
    if (body.email !== undefined) {
      const emailUpsert = `
        INSERT INTO user_email (user, email)
        VALUES ($1, $2)
        ON CONFLICT (user) DO UPDATE SET email = EXCLUDED.email`;
      await query(emailUpsert, [uid, body.email]);
    }

    // 修改密码：复用现有盐值重新加密
    if (body.password) {
      if (body.password.length < 6) {
        return NextResponse.json({ error: "密码长度至少6位" }, { status: 400 });
      }

      // 读取现有盐值
      const pwRow = await query<{ password_salt: string | null }>(
        `SELECT password_salt FROM user_password WHERE user = $1`,
        [uid]
      );

      let hash: string;
      if (pwRow.rows[0]?.password_salt) {
        // 复用现有盐值，重新加密
        hash = await argon2.hash(body.password, {
          salt: Buffer.from(pwRow.rows[0].password_salt!, "base64"),
        });
      } else {
        // 无现有记录，生成新盐并加密
        hash = await argon2.hash(body.password);
      }

      // upsert user_password（保留现有 is_active 状态）
      const upsert = `
        INSERT INTO user_password (user, password_hash, is_active)
        VALUES ($1, $2, true)
        ON CONFLICT (user) DO UPDATE SET password_hash = EXCLUDED.password_hash`;
      await query(upsert, [uid, hash]);
    }

    // 修改 display_name / organization
    const updates: string[] = [];
    const up: unknown[] = [];
    let idx = 1;
    if (body.displayName !== undefined) {
      updates.push(`display_name = $${idx++}`);
      up.push(body.displayName || null);
    }
    if (body.organization !== undefined) {
      updates.push(`organization = $${idx++}`);
      up.push(body.organization || null);
    }
    if (updates.length > 0) {
      up.push(uid);
      await query(
        `UPDATE "user" SET ${updates.join(", ")}, updated_at = NOW() WHERE uid = $${idx}`,
        up
      );
    }

    await createAuditLog({
      userId: adminUserId,
      username: adminUsername,
      action: "update",
      resource: "platform_user",
      resourceId: uid,
      requestParams: { email: !!body.email, password: !!body.password, displayName: !!body.displayName },
      ipAddress: req.headers.get("x-forwarded-for") || undefined,
      userAgent: req.headers.get("user-agent") || undefined,
    });

    return NextResponse.json({ success: true });
  } catch (e) {
    logError("Update user error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
