import { NextRequest, NextResponse } from "next/server";
import { signupMomoUser } from "@/lib/momo-auth";
import { createSession } from "@/lib/session";
import type { User } from "@/types";

export async function POST(request: NextRequest) {
  let body: Record<string, string>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ success: false, message: "잘못된 요청입니다." }, { status: 400 });
  }

  const { email, password, companyName, ceoName, bizNo, phone, address } = body;

  if (!email || !password || !companyName || !phone || !address) {
    return NextResponse.json(
      { success: false, message: "이메일, 비밀번호, 업체명, 전화번호, 주소는 필수입니다." },
      { status: 400 }
    );
  }

  const result = await signupMomoUser({ email, password, companyName, ceoName, bizNo, phone, address });
  if (!result.success || !result.user) {
    return NextResponse.json(
      { success: false, message: result.error ?? "가입에 실패했습니다." },
      { status: 400 }
    );
  }

  const sessionUser: User = {
    sabun: "",
    userId: result.user.email,
    userName: result.user.companyName,
    userNameEng: "",
    userNameCn: "",
    deptCode: "",
    deptName: "",
    positionCode: "",
    positionName: "",
    email: result.user.email,
    tel: "",
    cellPhone: result.user.phone || "",
    userType: result.user.role === "ADMIN" ? "A" : "U",
    userTypeName: result.user.role === "ADMIN" ? "관리자" : "사용자",
    authName: result.user.role,
    partnerCd: "",
    isAdmin: result.user.isAdmin,
    role: result.user.role,
    objid: result.user.objid,
    companyName: result.user.companyName,
  };
  await createSession(sessionUser);

  return NextResponse.json({ success: true, user: sessionUser });
}
