import pino from 'pino';
import { resolve } from 'path';
import { mkdirSync, statSync, renameSync, unlinkSync, existsSync } from 'fs';

const logDir = resolve(process.cwd(), 'data', 'logs');
mkdirSync(logDir, { recursive: true });

// ── Log Rotation ──
// Max 10 MB per log file, keep 5 rotated files.
const MAX_LOG_BYTES = 10 * 1024 * 1024; // 10 MB
const MAX_ROTATED_FILES = 5;

function rotateIfNeeded(filePath: string): void {
  try {
    if (!existsSync(filePath)) return;
    const stats = statSync(filePath);
    if (stats.size < MAX_LOG_BYTES) return;

    // Shift existing rotated files: .4 -> .5 (delete), .3 -> .4, .2 -> .3, .1 -> .2
    for (let i = MAX_ROTATED_FILES; i >= 1; i--) {
      const src = `${filePath}.${i}`;
      if (!existsSync(src)) continue;
      if (i === MAX_ROTATED_FILES) {
        unlinkSync(src);
      } else {
        renameSync(src, `${filePath}.${i + 1}`);
      }
    }
    // Current -> .1
    renameSync(filePath, `${filePath}.1`);
  } catch {
    // Rotation failure is non-fatal; log continues to current file.
  }
}

// Rotate on startup so large files from previous runs are archived immediately.
const appLogPath = resolve(logDir, 'app.log');
const errLogPath = resolve(logDir, 'errors.log');
rotateIfNeeded(appLogPath);
rotateIfNeeded(errLogPath);

const targets: pino.TransportTargetOptions[] = [
  {
    target: 'pino/file',
    options: { destination: appLogPath, mkdir: true },
    level: 'info',
  },
  {
    target: 'pino/file',
    options: { destination: errLogPath, mkdir: true },
    level: 'error',
  },
];

if (process.env.NODE_ENV !== 'production') {
  targets.push({
    target: 'pino-pretty',
    options: { colorize: true },
    level: 'debug',
  });
}

const transport = pino.transport({ targets });

export const logger = pino({ level: 'debug' }, transport);

export function createModuleLogger(module: string) {
  return logger.child({ module });
}
