import { cookies, draftMode } from 'next/headers'

/**
 * Check if the current user is (trying to be) authenticated by
 * checking if the `payload-token` is present.
 *
 * Warning: DO NOT USE THIS FUNCTION TO SECURE PARTS OF THE APPLICATION
 */
export const isAuthenticated = async (): Promise<boolean> => {
  const cookieStore = await cookies();
  const token = cookieStore.get("payload-token");

  if(typeof token === "undefined") {
    return false;
  }

  return true;
}

/**
 * Resolves the per-request auth context used by server pages that need both
 * authentication state and Next's draft-mode flag.
 */
export const getRequestAuth = async (): Promise<{ authenticated: boolean; isDraft: boolean }> => {
  const [authenticated, { isEnabled: isDraft }] = await Promise.all([
    isAuthenticated(),
    draftMode(),
  ])
  return { authenticated, isDraft }
}

type Publishable = { _status?: ('draft' | 'published') | null }

/**
 * Determines if the given entity can be viewed based on its status and authentication state.
 *
 * @param {T | null | undefined} entity - The entity to check, which may be null or undefined.
 * @param {boolean} authenticated - Indicates whether the user is authenticated.
 * @return {entity is T} Returns true if the entity can be viewed, otherwise false.
 */
export function canView<T extends Publishable>(
  entity: T | null | undefined,
  authenticated: boolean,
): entity is T {
  if (!entity) return false
  return authenticated || entity._status === 'published'
}