const Chalk = require('chalk');
const chalk = new Chalk.Instance({ level: 3 });

const levelStyles = {
  info: chalk.cyan.bold,
  success: chalk.greenBright.bold,
  warn: chalk.keyword('orange').bold,
  error: chalk.redBright.bold,
  request: chalk.magentaBright.bold,
  cache: chalk.blueBright.bold
};

const iconMap = {
  info: 'ℹ️',
  success: '✅',
  warn: '⚠️',
  error: '❌',
  request: '🚀',
  cacheHit: '📦',
  cacheMiss: '🆕'
};

const formatDuration = (ms) => `${ms.toFixed(1)}ms`;

const log = (level, message) => {
  const style = levelStyles[level] || ((text) => text);
  const icon = iconMap[level] || '•';
  console.log(`${style(icon)} ${message}`);
};

const logRequest = ({ method, url, status, durationMs, cacheHit }) => {
  const statusColor =
    status >= 500 ? chalk.bgRed.white.bold :
    status >= 400 ? chalk.keyword('orange').bold :
    chalk.greenBright.bold;

  const durationText = chalk.bgBlack.white.bold(`⏱ ${formatDuration(durationMs)}`);
  const methodText = chalk.white.bold(method);
  const urlText = chalk.gray(url);

  const cacheTag = cacheHit === undefined
    ? ''
    : cacheHit
      ? chalk.greenBright.bold(` [cache-hit ${iconMap.cacheHit}]`)
      : chalk.cyanBright.bold(` [cache-miss ${iconMap.cacheMiss}]`);

  const message = `${methodText} ${urlText} ${statusColor(String(status))} ${durationText}${cacheTag}`;
  log('request', message);
};

const logCacheHit = (key) => {
  const message = `${chalk.greenBright.bold(iconMap.cacheHit)} Redis cache bulundu -> ${chalk.white.bold(key)}`;
  log('cache', message);
};

const logCacheMiss = (key) => {
  const message = `${chalk.cyanBright.bold(iconMap.cacheMiss)} Redis cache olusturulacak -> ${chalk.white.bold(key)}`;
  log('cache', message);
};

module.exports = {
  info: (msg) => log('info', msg),
  success: (msg) => log('success', msg),
  warn: (msg) => log('warn', msg),
  error: (msg) => log('error', msg),
  request: logRequest,
  cacheHit: logCacheHit,
  cacheMiss: logCacheMiss
};
