"use server"

import { getToken } from "next-auth/jwt";
import { cookies, headers } from "next/headers";

export async function getAuthHeaders() {
  const req = {
    cookies: Object.fromEntries((await cookies()).getAll().map(c => [c.name, c.value])),
    headers: Object.fromEntries((await headers()).entries()),
  } as any;

  const token = await getToken({
    req,
    secret: process.env.NEXTAUTH_SECRET
  });

  // Check if token exists and has not expired
  if (!token || !token.accessToken || (token.tokenExpiry && Date.now() > token.tokenExpiry)) {
    // Token is missing, invalid, or expired - return empty headers
    // The API will return 401 and the server-action-wrapper will handle it
    return {};
  }

  return { Authorization: `Bearer ${token.accessToken}` };
}