import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { getSession } from "@/lib/session";

// 첨부파일 목록 조회 (active만)
// body: { objId, docType? }
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const objId = String(body.objId || "");
  const docType = String(body.docType || "");

  const conditions: string[] = ["target_objid = $1", "UPPER(COALESCE(status,'')) = 'ACTIVE'"];
  const params: unknown[] = [objId];
  if (docType) {
    conditions.push(`doc_type = $${params.length + 1}`);
    params.push(docType);
  }

  const rows = await queryRows(
    `SELECT objid::text AS "OBJID",
            real_file_name AS "REAL_FILE_NAME",
            doc_type AS "DOC_TYPE",
            doc_type_name AS "DOC_TYPE_NAME",
            file_size AS "FILE_SIZE",
            TO_CHAR(regdate, 'YYYY-MM-DD') AS "REGDATE",
            COALESCE((SELECT user_name FROM user_info WHERE user_id = writer LIMIT 1), writer) AS "WRITER_NAME"
       FROM attach_file_info
      WHERE ${conditions.join(" AND ")}
      ORDER BY regdate DESC`,
    params,
  );

  return NextResponse.json({ success: true, files: rows });
}
