import { NextRequest, NextResponse } from "next/server";
import { revalidatePath } from "next/cache";
import { db } from "@/lib/admin/db";
import { requireMainAdmin, getClientMetadata } from "@/lib/admin/auth";
import { validateProfilePatch } from "@/lib/admin/profile-validation";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/**
 * PATCH — Main Admin edits a subordinate's PROFILE (identity + author data).
 * Deliberately scoped to profile fields ONLY: it cannot change password, 2FA,
 * role, level or status — those remain in their own secure workflows (§24).
 */
export async function PATCH(
  req: NextRequest,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { user: mainAdmin } = await requireMainAdmin(req);
    const { ip } = getClientMetadata(req);
    const { id } = await context.params;

    const target = await db.getUserById(id);
    if (!target) {
      return NextResponse.json({ error: "Administrator not found." }, { status: 404 });
    }

    const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
    const parsed = validateProfilePatch(body);
    if (!parsed.ok) return NextResponse.json({ error: parsed.error }, { status: 400 });
    const data = { ...parsed.data };

    const previousSlug = target.authorSlug || null;

    if (data.authorSlug !== undefined) {
      if (!data.authorSlug) {
        data.authorSlug = await db.generateUniqueAuthorSlug(
          data.displayName || target.displayName || target.name,
          target.id
        );
      } else {
        const conflict = await db.getUserByAuthorSlug(data.authorSlug);
        if (conflict && conflict.id !== target.id) {
          return NextResponse.json(
            { error: "That author slug is already in use." },
            { status: 409 }
          );
        }
      }
    }

    const updated = await db.updateUser(target.id, data);

    if (previousSlug && data.authorSlug && data.authorSlug !== previousSlug) {
      try {
        await db.createRedirect({
          id: crypto.randomUUID(),
          source: `/author/${previousSlug}`,
          destination: `/author/${data.authorSlug}`,
          permanent: true,
          method: 301,
          createdAt: new Date().toISOString(),
          createdBy: mainAdmin.email,
        });
      } catch {
        /* non-fatal */
      }
    }

    await db.logSecurityEvent({
      actorId: mainAdmin.id,
      actorName: mainAdmin.name,
      actorEmail: mainAdmin.email,
      actorLevel: mainAdmin.level,
      targetUserId: target.id,
      targetUserEmail: target.email,
      targetUserName: target.name,
      action: "PROFILE_UPDATED",
      details: { fields: Object.keys(data), editedBy: "MAIN_ADMIN" },
      ipAddress: ip,
    });

    try {
      revalidatePath("/author");
      if (updated.authorSlug) revalidatePath(`/author/${updated.authorSlug}`);
      revalidatePath("/blog");
    } catch {
      /* best-effort */
    }

    return NextResponse.json({ ok: true, user: { id: updated.id, authorSlug: updated.authorSlug } });
  } catch (error) {
    const status = (error as { status?: number }).status || 500;
    return NextResponse.json(
      { error: (error as Error).message || "Failed to update profile." },
      { status }
    );
  }
}
