/**
 * Route Protection Middleware
 * Utilities to protect routes and check authentication
 */

import { getSession } from '../actions/authActions.js';
import { redirect } from 'next/navigation';

/**
 * Protect a page - requires authentication
 * Use this in server components to require authentication
 * 
 * @param {Object} options - Protection options
 * @param {string} options.redirectTo - Where to redirect if not authenticated (default: '/auth/login')
 * @returns {Promise<Object>} Session object with user data
 * 
 * @example
 * // In a server component:
 * import { protect } from '@zen/core/features/auth';
 * 
 * export default async function ProtectedPage() {
 *   const session = await protect();
 *   return <div>Welcome, {session.user.name}!</div>;
 * }
 */
async function protect(options = {}) {
  const { redirectTo = '/auth/login' } = options;
  
  const session = await getSession();
  
  if (!session) {
    redirect(redirectTo);
  }
  
  return session;
}

/**
 * Check if user is authenticated
 * Use this when you want to check authentication without forcing a redirect
 * 
 * @returns {Promise<Object|null>} Session object or null if not authenticated
 * 
 * @example
 * import { checkAuth } from '@zen/core/features/auth';
 * 
 * export default async function Page() {
 *   const session = await checkAuth();
 *   return session ? <div>Logged in</div> : <div>Not logged in</div>;
 * }
 */
async function checkAuth() {
  return await getSession();
}

/**
 * Require a specific role
 * @param {Array<string>} allowedRoles - Array of allowed roles
 * @param {Object} options - Options
 * @returns {Promise<Object>} Session object
 */
async function requireRole(allowedRoles = [], options = {}) {
  const { redirectTo = '/auth/login', forbiddenRedirect = '/' } = options;
  
  const session = await getSession();
  
  if (!session) {
    redirect(redirectTo);
  }
  
  if (!allowedRoles.includes(session.user.role)) {
    redirect(forbiddenRedirect);
  }
  
  return session;
}

export {
  protect,
  checkAuth,
  requireRole
};

