import { NextRequest, NextResponse } from "next/server";
import { queryOne } from "@/lib/db";
import { getSession } from "@/lib/session";
import { readFile } from "fs/promises";
import path from "path";

// 첨부파일 다운로드
export async function GET(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const url = new URL(request.url);
  const objId = url.searchParams.get("objId") || "";
  const inline = url.searchParams.get("inline") === "1";
  if (!objId) {
    return NextResponse.json({ success: false, message: "objId 누락" }, { status: 400 });
  }

  const row = await queryOne<{ REAL_FILE_NAME: string; SAVED_FILE_NAME: string; FILE_PATH: string }>(
    `SELECT real_file_name AS "REAL_FILE_NAME",
      saved_file_name AS "SAVED_FILE_NAME",
      file_path AS "FILE_PATH"
     FROM attach_file_info WHERE objid = $1`,
    [objId]
  );
  if (!row) {
    return NextResponse.json({ success: false, message: "파일을 찾을 수 없습니다." }, { status: 404 });
  }

  const storagePath = process.env.FILE_STORAGE_PATH || "/tmp/fito-files";
  const fullPath = path.join(storagePath, row.FILE_PATH);

  try {
    const buf = await readFile(fullPath);
    const body = new Uint8Array(buf);
    const ext = (row.REAL_FILE_NAME.split(".").pop() || "").toLowerCase();
    const mimeMap: Record<string, string> = {
      png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif",
      webp: "image/webp", bmp: "image/bmp", svg: "image/svg+xml",
      pdf: "application/pdf",
    };
    const contentType = inline && mimeMap[ext] ? mimeMap[ext] : "application/octet-stream";
    const disposition = inline
      ? `inline; filename*=UTF-8''${encodeURIComponent(row.REAL_FILE_NAME)}`
      : `attachment; filename*=UTF-8''${encodeURIComponent(row.REAL_FILE_NAME)}`;
    return new NextResponse(body, {
      headers: {
        "Content-Type": contentType,
        "Content-Disposition": disposition,
        "Content-Length": String(buf.length),
      },
    });
  } catch (e) {
    console.error("File download:", e);
    return NextResponse.json({ success: false, message: "파일을 읽을 수 없습니다." }, { status: 500 });
  }
}
