import fs from 'node:fs'
import path from 'node:path'
import { createLogger, format, transports } from 'winston'
import DailyRotateFile from 'winston-daily-rotate-file'

const isDev = process.env.NODE_ENV !== 'production'

const logsDir = process.env.LOG_DIR || path.join(process.cwd(), 'logs')

if (!isDev) {
  fs.mkdirSync(logsDir, { recursive: true })
}

const outputTransport = isDev
  ? new transports.Console()
  : new DailyRotateFile({
    dirname: logsDir,
    filename: 'app-%DATE%.log',
    datePattern: 'YYYY-MM-DD',
    zippedArchive: false,
  })

export const logger = createLogger({
  level: isDev ? 'debug' : 'info',
  format: format.combine(
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    format.errors({ stack: true }),
    format.printf(({ timestamp, level, message, stack, ...meta }) => {
      const metaText = Object.keys(meta).length ? ` ${JSON.stringify(meta)}` : ''
      const base = `[${timestamp}] ${level}: ${message}${metaText}`
      return stack ? `${base}\n${stack}` : base
    })
  ),
  transports: [outputTransport],
})
