// 매입 발주서 → 공급업체 발송 (상태 OPEN → REQUESTED + 메일)
import { NextRequest, NextResponse } from "next/server";
import { pool, queryOne, queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import nodemailer from "nodemailer";

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

  const { objid } = await req.json().catch(() => ({}));
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const proc = await queryOne<Record<string, unknown>>(
    `SELECT P.objid, P.proc_no, TO_CHAR(P.proc_date,'YYYY-MM-DD') AS proc_date,
            P.status, P.total_amount, P.memo,
            P.delivery_place, P.delivery_period, P.payment_terms, P.freight_terms,
            V.objid AS vendor_objid, V.supply_name AS vendor_name,
            V.email AS vendor_email, V.charge_user_name AS vendor_contact,
            V.supply_tel_no AS vendor_phone
     FROM momo_procurements P
     LEFT JOIN supply_mng V ON P.vendor_objid = V.objid::text
     WHERE P.objid = $1`,
    [objid]
  );
  if (!proc) return NextResponse.json({ success: false, message: "찾을 수 없음" }, { status: 404 });
  if (proc.status !== "OPEN" && proc.status !== "REQUESTED") {
    return NextResponse.json({ success: false, message: "작성/요청 상태에서만 발송 가능" }, { status: 400 });
  }
  const items = await queryRows<Record<string, unknown>>(
    `SELECT I.item_code, I.item_name, I.unit, PI.qty, PI.cost_price, PI.total_amount
     FROM momo_procurement_items PI JOIN momo_items I ON PI.item_objid = I.objid
     WHERE PI.proc_objid = $1 ORDER BY PI.objid`,
    [objid]
  );
  if (items.length === 0) {
    return NextResponse.json({ success: false, message: "라인이 없습니다." }, { status: 400 });
  }

  // 상태 변경
  await pool.query(
    `UPDATE momo_procurements SET status = 'REQUESTED' WHERE objid = $1`,
    [objid]
  );

  // 메일 발송 (실패해도 발주 요청은 성공)
  let mailSent = false;
  let mailError: string | undefined;
  if (proc.vendor_email) {
    try {
      const transporter = nodemailer.createTransport({
        host: process.env.SMTP_HOST,
        port: Number(process.env.SMTP_PORT || 465),
        secure: Number(process.env.SMTP_PORT || 465) === 465,
        auth: {
          user: process.env.SMTP_USER,
          pass: process.env.SMTP_PASS,
        },
      });

      const fmt = (n: unknown) => Number(n || 0).toLocaleString("ko-KR");
      const itemRows = items.map((it, idx) => `
        <tr>
          <td style="border:1px solid #ccc;padding:6px;text-align:center">${idx + 1}</td>
          <td style="border:1px solid #ccc;padding:6px">${it.item_name}</td>
          <td style="border:1px solid #ccc;padding:6px;text-align:center">${it.unit ?? "EA"}</td>
          <td style="border:1px solid #ccc;padding:6px;text-align:right">${fmt(it.qty)}</td>
          <td style="border:1px solid #ccc;padding:6px;text-align:right">${fmt(it.cost_price)}</td>
          <td style="border:1px solid #ccc;padding:6px;text-align:right;font-weight:bold">${fmt(it.total_amount)}</td>
        </tr>`).join("");

      const html = `
        <div style="font-family:Apple SD Gothic Neo,sans-serif;font-size:14px;color:#222;max-width:720px">
          <h2 style="text-align:center;letter-spacing:0.3em;margin:0 0 20px">발 주 서</h2>
          <table style="width:100%;margin-bottom:14px;font-size:13px">
            <tr>
              <td><b>발주번호</b> · ${proc.proc_no}</td>
              <td style="text-align:right"><b>발주일</b> · ${proc.proc_date}</td>
            </tr>
            <tr><td colspan="2"><b>공급업체</b> · ${proc.vendor_name ?? "-"}</td></tr>
          </table>
          <table style="width:100%;border-collapse:collapse;font-size:12px">
            <thead style="background:#f1f5f9">
              <tr>
                <th style="border:1px solid #ccc;padding:6px;width:40px">#</th>
                <th style="border:1px solid #ccc;padding:6px;text-align:left">품명</th>
                <th style="border:1px solid #ccc;padding:6px;width:50px">단위</th>
                <th style="border:1px solid #ccc;padding:6px;width:80px">수량</th>
                <th style="border:1px solid #ccc;padding:6px;width:100px">단가</th>
                <th style="border:1px solid #ccc;padding:6px;width:120px">금액</th>
              </tr>
            </thead>
            <tbody>${itemRows}</tbody>
          </table>
          <div style="text-align:right;margin-top:14px;font-size:14px"><b>총액 ₩${fmt(proc.total_amount)}</b> (V.A.T 별도)</div>

          <div style="margin-top:18px;font-size:12px">
            <p style="font-weight:700;margin:6px 0">2. 납품조건</p>
            <ol style="padding-left:20px;margin:0">
              <li>상기 품목의 납기 지연 시, 지연일수 매 1일에 대하여 미납 금액의 3/1000을 납품대금 지불 시 우선 공제한다.</li>
              <li>납품된 물품은 당사의 지정인에게 검수를 받아야 하며, 부적합품은 즉시 납품자의 비용으로 반출하여야 한다.</li>
              <li>상기 수량 및 규격은 당사의 사정에 의하여 변경될 수 있으며, 납품자는 이에 대하여 이의를 제기할 수 없다.</li>
            </ol>
            <table style="width:100%;border-collapse:collapse;font-size:12px;margin:8px 0">
              <tr>
                <th style="border:1px solid #cbd5e1;background:#f1f5f9;padding:5px;width:90px;text-align:center">4) 납품장소</th>
                <td style="border:1px solid #cbd5e1;padding:5px">${proc.delivery_place ?? "-"}</td>
                <th style="border:1px solid #cbd5e1;background:#f1f5f9;padding:5px;width:90px;text-align:center">6) 대금지불</th>
                <td style="border:1px solid #cbd5e1;padding:5px">${proc.payment_terms ?? "-"}</td>
              </tr>
              <tr>
                <th style="border:1px solid #cbd5e1;background:#f1f5f9;padding:5px;text-align:center">5) 납품기간</th>
                <td style="border:1px solid #cbd5e1;padding:5px">${proc.delivery_period ?? "-"}</td>
                <th style="border:1px solid #cbd5e1;background:#f1f5f9;padding:5px;text-align:center">7) 운임부담</th>
                <td style="border:1px solid #cbd5e1;padding:5px">${proc.freight_terms ?? "-"}</td>
              </tr>
            </table>
            <ol start="8" style="padding-left:20px;margin:0">
              <li>본 발주서는 납품자가 FAX 또는 기타 방법으로 접수 후 3일 이내에 이의를 제기치 않으면 제반 법적 효력을 발휘한다.</li>
              <li>상기 조항에 명시되지 아니한 사항은 상호 협의하고, 협의가 불가능할 경우에는 당사의 해석에 따른다.</li>
            </ol>
          </div>

          ${proc.memo ? `<div style="margin-top:14px;padding:10px;background:#f8fafc;border-left:4px solid #94a3b8;font-size:12px"><b>비고:</b> ${String(proc.memo).replace(/\n/g,"<br>")}</div>` : ""}
          <p style="margin-top:24px;text-align:center">상기와 같이 발주합니다.</p>
          <p style="margin-top:8px;text-align:center;font-weight:bold">${process.env.MOMO_COMPANY_NAME ?? "모모유통"}</p>
          <p style="margin-top:0;text-align:center;font-size:12px;color:#64748b">전화: ${process.env.MOMO_PHONE ?? ""}</p>
        </div>`;

      await transporter.sendMail({
        from: process.env.SMTP_FROM ?? process.env.SMTP_USER,
        to: proc.vendor_email as string,
        subject: `[${process.env.MOMO_COMPANY_NAME ?? "모모유통"}] 발주서 ${proc.proc_no}`,
        html,
      });
      mailSent = true;
    } catch (err) {
      mailError = err instanceof Error ? err.message : "메일 전송 실패";
      console.error("[procurements/send mail]", err);
    }
  }

  return NextResponse.json({
    success: true,
    procNo: proc.proc_no,
    mailSent,
    mailError,
    vendorEmail: proc.vendor_email ?? null,
  });
}
