import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import path from 'path';
import esbuild from 'rollup-plugin-esbuild';
import alias from '@rollup/plugin-alias';
import replace from '@rollup/plugin-replace';
import pkgs from './package.json' with {type: 'json'};

const isDev = process.env.NODE_ENV === 'development';
const input = isDev ? './src/dev.ts' : './src/main.ts';
/**
 * @type {import('rollup').RollupOptions}
 */
const config = {
  input,
  output: {
    dir: './dist',
    entryFileNames: 'app.mjs',
    chunkFileNames: '[name]-[hash].mjs',
    format: 'esm',
  },
  plugins: [
    replace({
      preventAssignment: true, // 防止意外赋值
      DEV_SERVER: JSON.stringify(isDev), // 替换 process.env.NODE_ENV
      APP_VERSION: JSON.stringify(pkgs.version),
    }),
    alias({
      // only esbuild needs to be configured
      entries: [
        { find: '@', replacement: path.resolve('src') }, // 配置 @ 为 src 目录
        { find: 'http', replacement: 'node:http' },
        { find: 'https', replacement: 'node:https' },
        { find: 'fs', replacement: 'node:fs' },
        { find: 'path', replacement: 'node:path' },
        { find: 'crypto', replacement: 'node:crypto' },
        { find: 'zlib', replacement: 'node:zlib' },
        { find: 'stream', replacement: 'node:stream' },
        { find: 'net', replacement: 'node:net' },
        { find: 'tty', replacement: 'node:tty' },
        { find: 'tls', replacement: 'node:tls' },
        { find: 'buffer', replacement: 'node:buffer' },
        { find: 'timers', replacement: 'node:timers' },
        // { find: 'string_decoder', replacement: 'node:string_decoder' },
        { find: 'dns', replacement: 'node:dns' },
        { find: 'domain', replacement: 'node:domain' },
        { find: 'os', replacement: 'node:os' },
        { find: 'events', replacement: 'node:events' },
        { find: 'url', replacement: 'node:url' },
        { find: 'assert', replacement: 'node:assert' },
        { find: 'util', replacement: 'node:util' },
      ],
    }),
    resolve({
      preferBuiltins: true, // 强制优先使用内置模块
    }),
    commonjs(),
    esbuild({
      target: 'node22', //
      minify: false, // 启用代码压缩
      tsconfig: 'tsconfig.json',
    }),
    json(),
  ],
  external: [
    /@kevisual\/router(\/.*)?/, //, // 路由
    /@kevisual\/use-config(\/.*)?/, //

    'sequelize', // 数据库 orm
    'ioredis', // redis
    'pg', // pg
  ],
};
export default config;
