// ============================================================
// electron-builder 配置
//
// 从 package.json "build" 字段提取，通过环境变量动态注入参数。
// build.mjs 负责设置 HEIXIU_* 环境变量后调用 electron-builder。
//
// 用法：
//   HEIXIU_EDITION=enterprise HEIXIU_CHANNEL=beta npx electron-builder --win --config build/electron-builder.js
// ============================================================

import { readFileSync } from 'node:fs';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = join(__dirname, '..');

const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));

const edition = process.env.HEIXIU_EDITION || 'personal';
const channel = process.env.HEIXIU_CHANNEL || 'stable';
const releaseDirName = process.env.HEIXIU_RELEASE_DIR_NAME || pkg.version;

const editionLabel = edition === 'enterprise' ? '企业版' : '';
const productName = editionLabel
  ? `船长·HeiXiu·${editionLabel}`
  : '船长·HeiXiu';

/** @type {import('electron-builder').Configuration} */
const config = {
  appId: edition === 'enterprise'
    ? 'com.heixiu.enterprise'
    : 'com.heixiu.electron',
  productName,
  asar: true,
  directories: {
    output: `release/${releaseDirName}`,
  },
  files: [
    'dist',
    'dist-electron',
  ],
  electronDownload: {
    mirror: 'https://npmmirror.com/mirrors/electron/',
  },
  // generic provider 仅作为 electron-updater 的 fallback，
  // 实际版本检查通过自定义 HeiXiuProvider → API
  publish: {
    provider: 'generic',
    url: 'https://update.heixiu.com',
  },
  win: {
    icon: 'src/assets/logo/heixiu.ico',
    target: [{ target: 'NSIS', arch: ['x64'] }],
    artifactName: '${productName}-Windows-${version}-Setup.${ext}',
  },
  mac: {
    icon: 'src/assets/logo/heixiu.icns',
    target: ['dmg'],
    artifactName: '${productName}-Mac-${version}-Installer.${ext}',
  },
  linux: {
    icon: 'src/assets/logo/HX.png',
    target: ['AppImage'],
    artifactName: '${productName}-Linux-${version}.${ext}',
  },
  nsis: {
    oneClick: false,
    perMachine: false,
    allowToChangeInstallationDirectory: true,
    deleteAppDataOnUninstall: false,
    differentialPackage: true,
    installerIcon: 'src/assets/logo/heixiu.ico',
    uninstallerIcon: 'src/assets/logo/heixiu.ico',
  },
};

export default config;
