// 기준 명세표 (공급자 정보) 저장 — admin
import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { invalidateBranchCache } from "@/lib/momo-branches";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const body = await req.json().catch(() => ({}));
  const {
    code, name, bankAccount, phone, email, ceoName, bizNo, address,
    isDefault, sortOrder, actionType,
  } = body as Record<string, string>;

  if (!code) return NextResponse.json({ success: false, message: "code 필수" }, { status: 400 });
  if (!name) return NextResponse.json({ success: false, message: "name 필수" }, { status: 400 });
  if (!bankAccount) return NextResponse.json({ success: false, message: "bankAccount 필수" }, { status: 400 });

  if (actionType === "delete") {
    await execute(`UPDATE momo_statement_branches SET is_del='Y' WHERE code=$1`, [code]);
  } else if (actionType === "regist") {
    await execute(
      `INSERT INTO momo_statement_branches (code, name, bank_account, phone, email, ceo_name, biz_no, address, is_default, sort_order, is_del, regdate)
       VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'N',NOW())
       ON CONFLICT (code) DO UPDATE SET
         name=EXCLUDED.name, bank_account=EXCLUDED.bank_account,
         phone=EXCLUDED.phone, email=EXCLUDED.email,
         ceo_name=EXCLUDED.ceo_name, biz_no=EXCLUDED.biz_no,
         address=EXCLUDED.address, is_default=EXCLUDED.is_default,
         sort_order=EXCLUDED.sort_order, is_del='N'`,
      [code, name, bankAccount, phone ?? null, email ?? null, ceoName ?? null, bizNo ?? null, address ?? null, isDefault === "Y" ? "Y" : "N", Number(sortOrder) || 0]
    );
  } else {
    await execute(
      `UPDATE momo_statement_branches SET
         name=$2, bank_account=$3, phone=$4, email=$5, ceo_name=$6, biz_no=$7, address=$8,
         is_default=$9, sort_order=$10
       WHERE code=$1`,
      [code, name, bankAccount, phone ?? null, email ?? null, ceoName ?? null, bizNo ?? null, address ?? null, isDefault === "Y" ? "Y" : "N", Number(sortOrder) || 0]
    );
  }
  invalidateBranchCache();
  return NextResponse.json({ success: true });
}
