import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { getSession } from "@/lib/session";
import { createObjectId } from "@/lib/utils";
import { writeFile, mkdir } from "fs/promises";
import path from "path";

// common/fileUploadProc.do 대응
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const formData = await request.formData();
  const file = formData.get("file") as File;
  const targetObjId = formData.get("targetObjId") as string;
  const docType = formData.get("docType") as string;
  const docTypeName = formData.get("docTypeName") as string;

  if (!file) {
    return NextResponse.json({ success: false, message: "파일이 없습니다." }, { status: 400 });
  }

  try {
    const storagePath = process.env.FILE_STORAGE_PATH || "/tmp/fito-files";
    const dateDir = new Date().toISOString().slice(0, 10).replace(/-/g, "");
    const uploadDir = path.join(storagePath, dateDir);

    await mkdir(uploadDir, { recursive: true });

    const objId = createObjectId();
    const extWithDot = path.extname(file.name);
    const fileExt = extWithDot.startsWith(".") ? extWithDot.slice(1) : extWithDot;
    const savedFileName = `${objId}${extWithDot}`;
    const filePath = path.join(uploadDir, savedFileName);
    const parentTargetObjId = String(formData.get("parentTargetObjId") || "");

    const buffer = Buffer.from(await file.arrayBuffer());
    await writeFile(filePath, buffer);

    // DB 저장 (attach_file_info) — 원본 common.insertUploadFileInfo 대응
    await execute(
      `INSERT INTO ATTACH_FILE_INFO (
         OBJID, TARGET_OBJID, PARENT_TARGET_OBJID,
         SAVED_FILE_NAME, REAL_FILE_NAME,
         DOC_TYPE, DOC_TYPE_NAME,
         FILE_SIZE, FILE_EXT, FILE_PATH,
         WRITER, REGDATE, STATUS
       ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, NOW(), 'Active')`,
      [
        objId,
        targetObjId,
        parentTargetObjId,
        savedFileName,
        file.name,
        docType,
        docTypeName,
        String(file.size),
        fileExt,
        `${dateDir}/${savedFileName}`,
        user.userId,
      ],
    );

    return NextResponse.json({ success: true, objId });
  } catch (error) {
    console.error("File upload error:", error);
    return NextResponse.json({ success: false, message: "파일 업로드 실패" }, { status: 500 });
  }
}
