import { NextResponse } from "next/server";
import {
  DashboardAuthError,
  requireDashboardApiContext,
} from "@/core/auth/dashboard-context";
import { writeAuditLog } from "@/services/audit-service";
import { attachProjectMedia } from "@/services/media-service";

export const runtime = "nodejs";

/**
 * Authenticated media upload.
 * Tenant ownership comes from session membership — never from client tenant_id.
 */
export async function POST(request: Request) {
  try {
    const ctx = await requireDashboardApiContext("media:manage");
    const form = await request.formData();
    const projectId = String(form.get("projectId") ?? "");
    const altText = String(form.get("altText") ?? "") || undefined;
    const file = form.get("file");

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

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

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

    await writeAuditLog({
      actorUserId: ctx.user.id,
      tenantId: ctx.tenant.tenantId,
      action: "media.upload",
      targetType: "project_media",
      targetId: result.media?.id,
      metadata: {
        projectId,
        mimeType: file.type,
        size: buffer.byteLength,
      },
    });

    return NextResponse.json(
      {
        id: result.media?.id,
        storageKey: result.media?.storageKey,
      },
      { status: 201 },
    );
  } catch (error) {
    if (error instanceof DashboardAuthError) {
      return NextResponse.json(
        { error: error.message },
        { status: error.status },
      );
    }
    console.error("Media upload failed", error);
    return NextResponse.json({ error: "Upload failed" }, { status: 500 });
  }
}
