// 모바일 전용 로그인: JWT 를 응답 본문으로 반환 (쿠키 미사용)
// RN 앱에서 SecureStore 에 보관한 뒤 Authorization: Bearer 헤더로 사용
import { NextRequest, NextResponse } from "next/server";
import { SignJWT } from "jose";
import { verifyMomoCredentials } from "@/lib/momo-auth";
import type { User } from "@/types";

const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "fito-plm-default-secret");

export async function POST(request: NextRequest) {
  const { email, password } = await request.json();
  if (!email || !password) {
    return NextResponse.json({ success: false, message: "이메일/비밀번호를 입력하세요." }, { status: 400 });
  }
  const r = await verifyMomoCredentials(email, password);
  if (!r.success || !r.user) {
    return NextResponse.json({ success: false, message: r.error ?? "로그인 실패" }, { status: 401 });
  }
  const user: User = {
    sabun: "", userId: r.user.email, userName: r.user.companyName,
    userNameEng: "", userNameCn: "", deptCode: "", deptName: "",
    positionCode: "", positionName: "", email: r.user.email,
    tel: "", cellPhone: r.user.phone, userType: "MOMO",
    userTypeName: r.user.role === "ADMIN" ? "관리자" : "거래처",
    authName: r.user.role, partnerCd: "", isAdmin: r.user.isAdmin,
    role: r.user.role, objid: r.user.objid, companyName: r.user.companyName,
  };
  const token = await new SignJWT({ user })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("30d")
    .sign(SECRET);
  return NextResponse.json({ success: true, token, user });
}
