import { registerAs } from '@nestjs/config';

export default registerAs('jwt', () => {
  const accessSecret = process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET;
  const refreshSecret = process.env.JWT_REFRESH_SECRET || process.env.JWT_SECRET;
  const adminSecret = process.env.ADMIN_JWT_ACCESS_SECRET || process.env.JWT_SECRET;

  if (
    !accessSecret ||
    accessSecret === 'change_me_in_production'
  ) {
    if (process.env.NODE_ENV === 'production') {
      throw new Error(
        '生产环境必须设置环境变量 JWT_ACCESS_SECRET 或 JWT_SECRET，不能使用默认值',
      );
    }
    console.warn(
      '\n⚠️  警告: JWT_SECRET 使用的是默认值 "change_me_in_production"\n' +
        '   部署到生产环境前请务必设置环境变量 JWT_ACCESS_SECRET\n',
    );
  }

  // Enforce admin JWT secret isolation in production
  if (process.env.NODE_ENV === 'production' && !process.env.ADMIN_JWT_ACCESS_SECRET) {
    throw new Error(
      '生产环境必须设置 ADMIN_JWT_ACCESS_SECRET 环境变量，不允许与用户 JWT 共用密钥',
    );
  }

  return {
    secret: accessSecret || 'change_me_in_production',
    accessSecret: accessSecret || 'change_me_in_production',
    refreshSecret: refreshSecret || 'change_me_in_production',
    adminSecret: adminSecret || 'change_me_in_production',
    adminRefreshSecret: process.env.ADMIN_JWT_REFRESH_SECRET || adminSecret || 'change_me_in_production',
    expiresIn: process.env.JWT_EXPIRES_IN || '1h',
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
    adminExpiresIn: process.env.ADMIN_JWT_EXPIRES_IN || '1h',
    adminRefreshExpiresIn: process.env.ADMIN_JWT_REFRESH_EXPIRES_IN || '7d',
  };
});
