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

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

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

  const userId = g.user.objid || g.user.userId;
  // 모드:
  //   alwaysSale=true → 상시 판매로 전환: is_always_sale='Y', 날짜 모두 초기화
  //   clear=true     → 미노출로 전환: is_always_sale='N', 날짜 모두 초기화
  //   기본          → 날짜 적용: is_always_sale='N', 날짜 입력 그대로
  const flag = alwaysSale ? "Y" : "N";
  const start = (alwaysSale || clear) ? null : (saleStartDate || null);
  const end   = (alwaysSale || 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,
            is_always_sale  = $${objids.length + 4},
            update_date = NOW(),
            update_id = $${objids.length + 3}
      WHERE objid IN (${placeholders})`,
    [...objids, start, end, userId, flag]
  );

  // 일괄 적용한 판매 일정이 유효(오늘/미래)한 품목이 있으면 일반 사용자에게 알림.
  //   판매기간 해제(clear)는 알림 대상 아님. (상세 수정과 동일 정책)
  if (!clear) {
    try {
      const sell = await pool.query<{ item_name: string; start_txt: string | null; orderable_now: boolean }>(
        `SELECT item_name,
                TO_CHAR(sale_start_date,'YYYY-MM-DD HH24:MI') AS start_txt,
                (COALESCE(is_always_sale,'N')='Y' OR sale_start_date IS NULL OR (NOW() AT TIME ZONE 'Asia/Seoul') >= sale_start_date) AS orderable_now
           FROM momo_items
          WHERE objid IN (${placeholders})
            AND COALESCE(is_del,'N') != 'Y'
            AND UPPER(COALESCE(status,'')) = 'ACTIVE'
            AND COALESCE(is_hidden,'N') != 'Y'
            AND (
              COALESCE(is_always_sale,'N') = 'Y'
              OR (
                (sale_start_date IS NOT NULL OR sale_end_date IS NOT NULL)
                AND (
                  sale_end_date IS NULL
                  OR (NOW() AT TIME ZONE 'Asia/Seoul') <= CASE
                    WHEN sale_end_date = date_trunc('day', sale_end_date)
                      THEN sale_end_date + INTERVAL '1 day' - INTERVAL '1 second'
                    ELSE sale_end_date
                  END
                )
              )
            )`,
        objids
      );
      const rows = sell.rows;
      if (rows.length === 1) {
        const r = rows[0];
        const body = r.orderable_now ? r.item_name : `${r.item_name} (${r.start_txt ?? "곧"} 판매 예정)`;
        const sr = await sendPush({ title: "새 상품이 등록되었습니다", body, url: "/m/orders/new", tag: "item-bulk" });
        console.log(`[bulk-sale-range notify] item=${r.item_name} sent=${sr.sent} failed=${sr.failed}`);
      } else if (rows.length > 1) {
        const sr = await sendPush(
          { title: "새 상품이 등록되었습니다", body: `${rows.length}개 상품이 등록되었습니다. 지금 확인해보세요.`, url: "/m/orders/new", tag: "item-bulk" }
        );
        console.log(`[bulk-sale-range notify] count=${rows.length} sent=${sr.sent} failed=${sr.failed}`);
      }
    } catch (e) {
      console.error("[bulk-sale-range notify]", e);
    }
  }

  return NextResponse.json({ success: true, count: res.rowCount ?? 0 });
}
