import { NextResponse } from "next/server";
import { revalidatePath } from "next/cache";
import {
  DashboardAuthError,
  requireDashboardApiContext,
} from "@/core/auth/dashboard-context";
import { getStorage } from "@/core/storage/storage";
import { writeAuditLog } from "@/services/audit-service";
import {
  clearArchitectPhoto,
  setArchitectPhoto,
} from "@/services/profile-service";

export const runtime = "nodejs";

function revalidateStudioPaths() {
  revalidatePath("/dashboard/settings");
  revalidatePath("/site");
  revalidatePath("/site/about");
}

export async function POST(request: Request) {
  try {
    const ctx = await requireDashboardApiContext("settings:manage");
    const form = await request.formData();
    const file = form.get("file");

    if (!(file instanceof File)) {
      return NextResponse.json({ error: "Invalid upload" }, { status: 400 });
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    const result = await setArchitectPhoto(ctx.tenant, {
      fileName: file.name,
      mimeType: file.type || "application/octet-stream",
      body: buffer,
    });

    if (!result.ok) {
      return NextResponse.json({ error: result.error }, { status: 400 });
    }

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "profile.photo.upload",
      targetType: "architect_profile",
      targetId: ctx.tenant.tenantId,
      metadata: {
        mimeType: file.type,
        size: buffer.byteLength,
      },
    });

    revalidateStudioPaths();

    const storage = getStorage();
    const url = await storage.getSignedUrl(
      result.storageKey,
      ctx.tenant.tenantId,
    );

    return NextResponse.json(
      {
        storageKey: result.storageKey,
        url: `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`,
      },
      { status: 201 },
    );
  } catch (error) {
    if (error instanceof DashboardAuthError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.status },
      );
    }
    console.error("Architect photo upload failed", error);
    return NextResponse.json({ error: "Upload failed" }, { status: 500 });
  }
}

export async function DELETE() {
  try {
    const ctx = await requireDashboardApiContext("settings:manage");
    await clearArchitectPhoto(ctx.tenant);

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "profile.photo.remove",
      targetType: "architect_profile",
      targetId: ctx.tenant.tenantId,
    });

    revalidateStudioPaths();

    return NextResponse.json({ ok: true });
  } catch (error) {
    if (error instanceof DashboardAuthError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.status },
      );
    }
    console.error("Architect photo remove failed", error);
    return NextResponse.json({ error: "Remove failed" }, { status: 500 });
  }
}
