import { cookies } from "next/headers";
import { SignJWT, jwtVerify } from "jose";
import type { User } from "@/types";

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

const SESSION_COOKIE = "plm-session";
const SESSION_DURATION_DEFAULT = 24 * 60 * 60;            // 24시간 (기본)
const SESSION_DURATION_REMEMBER = 365 * 24 * 60 * 60 * 10; // 10년 — 사실상 "계속 유지"

export async function createSession(user: User, remember = false): Promise<string> {
  const duration = remember ? SESSION_DURATION_REMEMBER : SESSION_DURATION_DEFAULT;
  const token = await new SignJWT({ user })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(`${duration}s`)
    .sign(SECRET);

  const cookieStore = await cookies();
  cookieStore.set(SESSION_COOKIE, token, {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "lax",
    maxAge: duration,
    path: "/",
  });

  return token;
}

export async function getSession(): Promise<User | null> {
  // 1) 쿠키 기반 (웹)
  const cookieStore = await cookies();
  const cookieToken = cookieStore.get(SESSION_COOKIE)?.value;
  if (cookieToken) {
    try {
      const { payload } = await jwtVerify(cookieToken, SECRET);
      return (payload as { user: User }).user;
    } catch { /* fall through */ }
  }
  // 2) Authorization: Bearer (모바일 앱)
  const { headers } = await import("next/headers");
  const h = await headers();
  const auth = h.get("authorization") || h.get("Authorization");
  if (auth?.startsWith("Bearer ")) {
    try {
      const { payload } = await jwtVerify(auth.slice(7), SECRET);
      return (payload as { user: User }).user;
    } catch { /* ignore */ }
  }
  return null;
}

export async function destroySession(): Promise<void> {
  const cookieStore = await cookies();
  cookieStore.delete(SESSION_COOKIE);
}
