import { NextRequest, NextResponse } from "next/server";
import crypto from "crypto";
import { cookies } from "next/headers";

const FLEET_API_URL = process.env.FLEET_API_URL || "https://fleet-api.vexplor.com";
const SSO_SHARED_SECRET = process.env.SSO_SHARED_SECRET || "change_this_sso_secret";

export async function POST(request: NextRequest) {
  try {
    // V1 로그인 세션에서 사용자 정보 추출
    const cookieStore = await cookies();
    const sessionToken = cookieStore.get("session_token")?.value
      || cookieStore.get("token")?.value;

    if (!sessionToken) {
      return NextResponse.json({ error: "로그인이 필요합니다." }, { status: 401 });
    }

    // 세션에서 사용자 정보 파싱 (JWT 디코딩)
    let userId = "unknown";
    let userName = "unknown";
    let companyId = "";
    try {
      const payload = JSON.parse(atob(sessionToken.split(".")[1]));
      userId = payload.userId || payload.user_id || payload.sub || payload.id || "unknown";
      userName = payload.userName || payload.user_name || payload.name || "unknown";
      companyId = payload.companyId || payload.company_id || payload.companyCode || "";
    } catch {
      return NextResponse.json({ error: "세션이 유효하지 않습니다." }, { status: 401 });
    }

    // Fleet API로 SSO 토큰 요청 (HMAC 서명)
    const timestamp = Math.floor(Date.now() / 1000);
    const signPayload = `${userId}|${userName}|${companyId}|${timestamp}`;
    const signature = crypto
      .createHmac("sha256", SSO_SHARED_SECRET)
      .update(signPayload)
      .digest("hex");

    const response = await fetch(`${FLEET_API_URL}/api/auth/sso`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        user_id: userId,
        user_name: userName,
        company_id: companyId,
        timestamp,
        signature,
      }),
    });

    const data = await response.json();

    if (!response.ok || !data.success) {
      return NextResponse.json(
        { error: data.message || "SSO 토큰 발급 실패" },
        { status: response.status },
      );
    }

    return NextResponse.json({ token: data.data.token });
  } catch (error) {
    console.error("[fleet-sso] 토큰 발급 에러:", error);
    return NextResponse.json({ error: "서버 오류" }, { status: 500 });
  }
}
