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

interface TaskInput {
  task_name?: string;
  unit_no?: string;
}

// Excel import 저장 (project.mergeExcelUploadWBS 대응)
// - 동일 PRODUCT + TITLE 존재 시 오류
// - pms_wbs_template INSERT + pms_wbs_task_standard 일괄 INSERT (한 트랜잭션)
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 product = String(body.product || "");
  const title = String(body.title || "");
  const customerProduct = String(body.customer_product || "");
  const tasks: TaskInput[] = Array.isArray(body.tasks) ? body.tasks : [];

  if (!product) return NextResponse.json({ success: false, message: "제품은 필수값입니다." }, { status: 400 });
  if (!title) return NextResponse.json({ success: false, message: "기계형식을 입력해 주세요." }, { status: 400 });
  if (!customerProduct) return NextResponse.json({ success: false, message: "고객사_장비목적을 입력해 주세요." }, { status: 400 });
  if (tasks.length === 0) return NextResponse.json({ success: false, message: "저장할 정보가 없습니다." }, { status: 400 });

  const client = await pool.connect();
  try {
    // 중복 체크 (project.getWBSTemplateProductList 대응)
    const dup = await client.query(
      `SELECT 1 FROM pms_wbs_template WHERE product_objid = $1 AND title = $2 LIMIT 1`,
      [product, title]
    );
    if ((dup.rowCount ?? 0) > 0) {
      return NextResponse.json({ success: false, message: "이미 해당 기계형식으로 등록된 정보가 존재합니다." }, { status: 400 });
    }

    await client.query("BEGIN");

    const masterId = createObjectId();
    await client.query(
      `INSERT INTO pms_wbs_template (objid, product_objid, title, customer_product, writer, reg_date)
       VALUES ($1, $2, $3, $4, $5, now())`,
      [masterId, product, title, customerProduct, user.userId]
    );

    for (let i = 0; i < tasks.length; i++) {
      const t = tasks[i];
      const taskName = String(t.task_name || "").trim();
      if (!taskName) continue;
      await client.query(
        `INSERT INTO pms_wbs_task_standard (objid, parent_objid, task_name, task_seq, user_id, writer, reg_date, unit_no)
         VALUES ($1, $2, $3, $4, $5, $6, now(), $7)`,
        [createObjectId(), masterId, taskName, String(i + 1), "", user.userId, String(t.unit_no || "")]
      );
    }

    await client.query("COMMIT");
    return NextResponse.json({ success: true, objId: masterId, message: "저장하였습니다." });
  } catch (error) {
    await client.query("ROLLBACK");
    console.error("WBS excel save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
