// 품목 판매 가능일 일괄 적용 — admin 만.
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

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

  const { objids, saleStartDate, saleEndDate, clear } = await req.json() as {
    objids: string[]; saleStartDate?: string; saleEndDate?: string; clear?: boolean;
  };
  if (!Array.isArray(objids) || objids.length === 0) {
    return NextResponse.json({ success: false, message: "대상 품목을 선택하세요." }, { status: 400 });
  }

  const userId = g.user.objid || g.user.userId;
  const start = clear ? null : (saleStartDate || null);
  const end   = clear ? null : (saleEndDate   || null);

  const placeholders = objids.map((_, i) => `$${i + 1}`).join(",");
  const res = await pool.query(
    `UPDATE momo_items
        SET sale_start_date = $${objids.length + 1}::timestamp,
            sale_end_date   = $${objids.length + 2}::timestamp,
            update_date = NOW(),
            update_id = $${objids.length + 3}
      WHERE objid IN (${placeholders})`,
    [...objids, start, end, userId]
  );
  return NextResponse.json({ success: true, count: res.rowCount ?? 0 });
}
