/**
 * Metadata Utilities
 * Functions to generate dynamic metadata for Next.js pages
 */

import { getAppName } from '../appConfig.js';

/**
 * Generate page title with app name
 * @param {string} title - Page title
 * @param {Object} options - Options
 * @param {boolean} options.includeAppName - Include app name in title (default: true)
 * @param {string} options.separator - Separator between title and app name (default: ' - ')
 * @param {string} options.appName - Custom app name (default: from config)
 * @returns {string} Formatted title
 */
export function generateTitle(title, options = {}) {
  const {
    includeAppName = true,
    separator = ' - ',
    appName = null
  } = options;

  if (!includeAppName) {
    return title;
  }

  const name = appName || getAppName();
  return `${title}${separator}${name}`;
}

/**
 * Generate metadata object for Next.js
 * @param {Object} params - Metadata parameters
 * @param {string} params.title - Page title
 * @param {string} params.description - Page description
 * @param {Object} params.openGraph - Open Graph metadata
 * @param {Object} params.twitter - Twitter metadata
 * @param {Object} params.other - Other metadata fields
 * @param {Object} options - Generation options
 * @param {boolean} options.includeAppName - Include app name in title (default: true)
 * @param {string} options.appName - Custom app name
 * @returns {Object} Next.js metadata object
 */
export function generateMetadata(params = {}, options = {}) {
  const {
    title,
    description,
    openGraph,
    twitter,
    ...other
  } = params;

  const metadata = {};

  // Title
  if (title) {
    metadata.title = generateTitle(title, options);
  }

  // Description
  if (description) {
    metadata.description = description;
  }

  // Open Graph
  if (openGraph) {
    metadata.openGraph = {
      ...openGraph,
      title: openGraph.title ? generateTitle(openGraph.title, options) : metadata.title,
      description: openGraph.description || description,
    };
  }

  // Twitter
  if (twitter) {
    metadata.twitter = {
      ...twitter,
      title: twitter.title ? generateTitle(twitter.title, options) : metadata.title,
      description: twitter.description || description,
    };
  }

  // Other metadata
  Object.assign(metadata, other);

  return metadata;
}

/**
 * Generate robots metadata
 * @param {Object} options - Robots options
 * @param {boolean} options.index - Allow indexing (default: true)
 * @param {boolean} options.follow - Allow following links (default: true)
 * @param {boolean} options.noarchive - Prevent archiving
 * @param {boolean} options.nocache - Prevent caching
 * @returns {Object} Robots metadata
 */
export function generateRobots(options = {}) {
  const {
    index = true,
    follow = true,
    noarchive = false,
    nocache = false,
  } = options;

  return {
    index,
    follow,
    ...(noarchive && { noarchive: true }),
    ...(nocache && { nocache: true }),
  };
}

