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

// ProductMgmtController.productmgmtList 대응
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 { year, product_category, page = 1, countPerPage = 20 } = body;

  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let paramIdx = 1;

  if (year) {
    conditions.push(`EXTRACT(YEAR FROM P.REGDATE) = $${paramIdx++}`);
    params.push(year);
  }
  if (product_category) {
    conditions.push(`P.PRODUCT_CATEGORY = $${paramIdx++}`);
    params.push(product_category);
  }

  const where = conditions.join(" AND ");

  const countResult = await queryOne<{ CNT: string }>(
    `SELECT COUNT(*) AS CNT FROM PRODUCT_MGMT P WHERE ${where}`,
    params
  );
  const totalCount = Number(countResult?.CNT || 0);
  const maxPage = Math.max(1, Math.ceil(totalCount / countPerPage));
  const offset = (Number(page) - 1) * countPerPage;

  const list = await queryRows(
    `SELECT P.OBJID::text AS "OBJID", P.PRODUCT_CATEGORY,
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0000917' AND CODE_ID = P.PRODUCT_CATEGORY LIMIT 1), '') AS "PRODUCT_CATEGORY_NAME",
            P.PRODUCT_TYPE,
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0005116' AND CODE_ID = P.PRODUCT_TYPE LIMIT 1), '') AS "PRODUCT_TYPE_NAME",
            P.PRODUCT_NAME AS "PRODUCT_NAME",
            P.PRODUCT_CODE AS "PRODUCT_CODE",
            COALESCE((SELECT USER_NAME FROM USER_INFO WHERE USER_ID = P.WRITER LIMIT 1), P.WRITER) AS "WRITER_NAME",
            TO_CHAR(P.REGDATE, 'YYYY-MM-DD') AS "REGDATE",
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0000039' AND CODE_ID = P.PRODUCTION_FLAG LIMIT 1), '') AS "PRODUCTION_FLAG_NAME",
            COALESCE((SELECT COUNT(*) FROM ATTACH_FILE_INFO WHERE TARGET_OBJID = P.OBJID::text), 0) AS "FILE_CNT"
     FROM PRODUCT_MGMT P
     WHERE ${where}
     ORDER BY P.REGDATE DESC
     LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
    [...params, countPerPage, offset]
  );

  return NextResponse.json({
    RESULTLIST: list,
    TOTAL_CNT: totalCount,
    MAX_PAGE_SIZE: maxPage,
    COUNT_PER_PAGE: countPerPage,
  });
}

export async function DELETE(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const { objIds } = body;

  if (!objIds || !Array.isArray(objIds) || objIds.length === 0) {
    return NextResponse.json({ success: false, message: "선택한 항목이 없습니다." });
  }

  try {
    const placeholders = objIds.map((_: string, i: number) => `$${i + 1}`).join(",");
    await execute(`DELETE FROM PRODUCT_MGMT WHERE OBJID IN (${placeholders})`, objIds);
    return NextResponse.json({ success: true, message: "삭제되었습니다." });
  } catch (error) {
    console.error("Product delete error:", error);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." });
  }
}
