import { NextRequest, NextResponse } from "next/server";
import { writeFile, mkdir } from "node:fs/promises";
import path from "node:path";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { createObjectId } from "@/lib/utils";

const ALLOWED = ["image/jpeg", "image/png", "image/webp", "image/gif"];
const MAX_SIZE = 5 * 1024 * 1024;

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  try {
    const form = await req.formData();
    const file = form.get("file") as File | null;
    if (!file) return NextResponse.json({ success: false, message: "파일이 없습니다." }, { status: 400 });
    if (!ALLOWED.includes(file.type)) {
      return NextResponse.json({ success: false, message: "이미지 파일만 업로드 가능합니다." }, { status: 400 });
    }
    if (file.size > MAX_SIZE) {
      return NextResponse.json({ success: false, message: "파일 크기는 5MB 이하여야 합니다." }, { status: 400 });
    }

    const today = new Date();
    const ymd = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}`;

    // 저장 경로 후보 (앞에서 성공하는 것 채택)
    const candidates = [
      "/data_storage/uploads/items",                          // 운영 도커 (Dockerfile 에서 nextjs 소유)
      "/app/public/uploads/items",                            // 호스트 마운트 fallback
      path.join(process.cwd(), "public", "uploads", "items"), // 로컬 dev
    ];

    let baseDir: string | null = null;
    let lastErr = "";
    for (const c of candidates) {
      try {
        await mkdir(path.join(c, ymd), { recursive: true });
        baseDir = c;
        break;
      } catch (err) {
        lastErr = err instanceof Error ? err.message : String(err);
      }
    }
    if (!baseDir) {
      console.error("[upload] 저장 디렉토리 모두 실패:", lastErr);
      return NextResponse.json({ success: false, message: `저장소 권한 오류: ${lastErr}` }, { status: 500 });
    }

    const ext = (file.name.match(/\.[a-zA-Z0-9]+$/)?.[0] ?? ".jpg").toLowerCase();
    const safeExt = /^\.(jpg|jpeg|png|webp|gif)$/.test(ext) ? ext : ".jpg";
    const fname = createObjectId() + safeExt;
    const fpath = path.join(baseDir, ymd, fname);
    const buf = Buffer.from(await file.arrayBuffer());
    await writeFile(fpath, buf);

    // URL 결정: data_storage 또는 public 마운트 → /api/uploads/items/...
    //         로컬 dev (cwd/public) → /uploads/items/...
    const isLocalPublic = baseDir.endsWith(path.join("public", "uploads", "items")) && !baseDir.startsWith("/app");
    const url = isLocalPublic
      ? `/uploads/items/${ymd}/${fname}`
      : `/api/uploads/items/${ymd}/${fname}`;
    console.log("[upload] saved:", fpath, "→", url);
    return NextResponse.json({ success: true, url, savedAt: fpath });
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[upload] error:", msg);
    return NextResponse.json({ success: false, message: `업로드 실패: ${msg}` }, { status: 500 });
  }
}
