// File: frontend/lib/auth-server.js
// frontend/lib/auth-server.js
import 'server-only';
import { cookies } from 'next/headers';

export function getAccessToken() {
  const cookieStore = cookies();
  return cookieStore.get('access_token')?.value ?? null;
}

function buildCookieHeader() {
  const store = cookies();
  return store.getAll().map(c => `${c.name}=${c.value}`).join('; ');
}

export async function getSession() {
  const token = getAccessToken();
  if (!token) return null;

  try {
    const res = await fetch(`${process.env.NEXT_PUBLIC_API_BASE}/api/auth/me`, {
      method: 'GET',
      headers: { cookie: buildCookieHeader(), accept: 'application/json' },
      cache: 'no-store',
    });
    if (!res.ok) return null;
    const data = await res.json();
    const user = data?.user ?? data; // รองรับทั้ง {user:{...}} หรือส่งตรง
    return { user, token };
  } catch {
    return null;
  }
}

export async function requireSession() {
  const session = await getSession();
  if (!session) {
    const { redirect } = await import('next/navigation');
    redirect('/login');
  }
  return session;
}
