import { NextResponse } from "next/server";
import { queryOne } from "@/lib/db";
import { getSession } from "@/lib/session";

// 다음 영업번호 생성 (YYC-NNNN 형식)
export async function GET() {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const yearPrefix = new Date().getFullYear().toString().slice(2); // "26"
  const prefix = `${yearPrefix}C-`;

  const result = await queryOne<{ MAX_NO: string }>(
    `SELECT MAX(contract_no) AS "MAX_NO"
     FROM contract_mgmt
     WHERE contract_no LIKE $1 || '%'`,
    [prefix]
  );

  let nextSeq = 1;
  if (result?.MAX_NO) {
    const lastSeq = parseInt(result.MAX_NO.replace(prefix, ""), 10);
    if (!isNaN(lastSeq)) nextSeq = lastSeq + 1;
  }

  const nextNo = `${prefix}${String(nextSeq).padStart(4, "0")}`;
  return NextResponse.json({ success: true, contractNo: nextNo });
}
