import express from 'express';
import bcrypt from 'bcrypt';
import { v4 as uuidv4 } from 'uuid';
import { userDb, domainWhitelistDb, settingsDb, usageDb, feishuDb, imageDb, agentSubmissionDb } from '../database/db.js';
import { authenticateToken } from '../middleware/auth.js';
import { deleteUserDirectories, initUserDirectories } from '../services/user-directories.js';
import { getDefaultPermissions, ALL_FEATURE_PERMISSIONS } from '../services/feature-permissions.js';
import { deleteUserImageDir } from '../services/image-storage.js';

const router = express.Router();

// Admin middleware - allows both admin and super_admin
const requireAdmin = (req, res, next) => {
  if (req.user.role !== 'admin' && req.user.role !== 'super_admin') {
    return res.status(403).json({ error: 'Admin access required' });
  }
  next();
};

// Super admin only middleware
const requireSuperAdmin = (req, res, next) => {
  if (req.user.role !== 'super_admin') {
    return res.status(403).json({ error: 'Super admin access required' });
  }
  next();
};

// Apply auth and admin middleware to all routes
router.use(authenticateToken);
router.use(requireAdmin);

// Get all users
router.get('/users', (req, res) => {
  try {
    const users = userDb.getAllUsers();
    res.json({ users });
  } catch (error) {
    console.error('Error fetching users:', error);
    res.status(500).json({ error: 'Failed to fetch users' });
  }
});

// Create a new user with username and password (admin only)
router.post('/users', async (req, res) => {
  try {
    const { username, password } = req.body;

    if (!username || !password) {
      return res.status(400).json({ error: '用户名和密码不能为空' });
    }

    if (username.length < 3 || password.length < 6) {
      return res.status(400).json({
        error: '用户名至少3个字符，密码至少6个字符'
      });
    }

    // Check if username already exists
    const existingUser = userDb.getUserByUsername(username);
    if (existingUser) {
      return res.status(409).json({ error: '用户名已存在' });
    }

    // Hash password
    const saltRounds = 12;
    const passwordHash = await bcrypt.hash(password, saltRounds);

    // Create user
    const uuid = uuidv4();
    const user = userDb.createUserFull(username, passwordHash, uuid, 'user');

    // Apply default limits
    const defaultTotalLimit = settingsDb.get('default_total_limit_usd');
    const defaultDailyLimit = settingsDb.get('default_daily_limit_usd');
    if (defaultTotalLimit !== null || defaultDailyLimit !== null) {
      userDb.updateUserLimits(
        user.id,
        defaultTotalLimit !== null ? parseFloat(defaultTotalLimit) : null,
        defaultDailyLimit !== null ? parseFloat(defaultDailyLimit) : null
      );
    }

    // Initialize user directories
    await initUserDirectories(uuid);

    res.json({
      success: true,
      user: {
        id: user.id,
        username: user.username,
        uuid: user.uuid,
        role: user.role
      }
    });

  } catch (error) {
    console.error('Error creating user:', error);
    if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
      res.status(409).json({ error: '用户名已存在' });
    } else {
      res.status(500).json({ error: '创建用户失败' });
    }
  }
});

// Update user status
router.patch('/users/:id', (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!['active', 'disabled'].includes(status)) {
      return res.status(400).json({ error: 'Invalid status' });
    }

    // Prevent self-disable
    if (parseInt(id) === req.user.id) {
      return res.status(400).json({ error: 'Cannot modify your own status' });
    }

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // admin cannot operate on other admin/super_admin users
    if (req.user.role === 'admin' && ['admin', 'super_admin'].includes(user.role)) {
      return res.status(403).json({ error: '无权操作管理员账户' });
    }

    userDb.updateUserStatus(id, status);
    res.json({ success: true, message: `User status updated to ${status}` });
  } catch (error) {
    console.error('Error updating user status:', error);
    res.status(500).json({ error: 'Failed to update user status' });
  }
});

// Delete user
router.delete('/users/:id', async (req, res) => {
  try {
    const { id } = req.params;

    // Prevent self-delete
    if (parseInt(id) === req.user.id) {
      return res.status(400).json({ error: 'Cannot delete your own account' });
    }

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // admin cannot delete other admin/super_admin users
    if (req.user.role === 'admin' && ['admin', 'super_admin'].includes(user.role)) {
      return res.status(403).json({ error: '无权删除管理员账户' });
    }

    // Delete user directories (config + projects)
    if (user.uuid) {
      await deleteUserDirectories(user.uuid);
      // 删除聊天图片文件目录
      await deleteUserImageDir(user.uuid);
    }

    // 删除数据库中所有关联数据
    usageDb.deleteByUserUuid(user.uuid);          // usage_records + usage_daily_summary
    feishuDb.deleteByUserUuid(user.uuid);          // feishu_bindings + feishu_session_state
    imageDb.deleteByUserUuid(user.uuid);           // message_images
    agentSubmissionDb.deleteByUserId(user.id);     // agent_submissions

    // Delete from database
    userDb.deleteUserById(id);

    res.json({ success: true, message: 'User deleted successfully' });
  } catch (error) {
    console.error('Error deleting user:', error);
    res.status(500).json({ error: 'Failed to delete user' });
  }
});

// Reset user password (admin only)
router.patch('/users/:id/password', async (req, res) => {
  try {
    const { id } = req.params;
    const { new_password } = req.body;

    // Validate new password
    if (!new_password || new_password.length < 6) {
      return res.status(400).json({ error: '新密码至少需要6个字符' });
    }

    // Prevent resetting own password via admin route
    if (parseInt(id) === req.user.id) {
      return res.status(400).json({ error: '请通过账户设置修改自己的密码' });
    }

    const user = userDb.getUserByIdWithPassword(id);
    if (!user) {
      return res.status(404).json({ error: '用户不存在' });
    }

    // admin cannot reset password of other admin/super_admin users
    if (req.user.role === 'admin' && ['admin', 'super_admin'].includes(user.role)) {
      return res.status(403).json({ error: '无权重置管理员密码' });
    }

    // Can only reset password for password-login users
    if (!user.password_hash) {
      return res.status(400).json({ error: '该用户使用邮箱验证码登录，无法重置密码' });
    }

    // Hash new password
    const saltRounds = 12;
    const passwordHash = await bcrypt.hash(new_password, saltRounds);

    // Update database
    userDb.updateUserPassword(id, passwordHash);

    res.json({ success: true, message: '密码已重置' });
  } catch (error) {
    console.error('Error resetting password:', error);
    res.status(500).json({ error: '重置密码失败' });
  }
});

// Update user role (super_admin only)
router.patch('/users/:id/role', requireSuperAdmin, (req, res) => {
  try {
    const { id } = req.params;
    const { role } = req.body;

    if (!['admin', 'user'].includes(role)) {
      return res.status(400).json({ error: '只能设置为 admin 或 user' });
    }

    if (parseInt(id) === req.user.id) {
      return res.status(400).json({ error: '不能修改自己的角色' });
    }

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    if (user.role === 'super_admin') {
      return res.status(403).json({ error: '不能修改超级管理员的角色' });
    }

    userDb.updateUserRole(id, role);
    res.json({ success: true, message: '用户角色已更新' });
  } catch (error) {
    console.error('Error updating user role:', error);
    res.status(500).json({ error: '更新用户角色失败' });
  }
});

// ==================== User Spending Limits ====================

// Get user spending limits
router.get('/users/:id/limits', (req, res) => {
  try {
    const { id } = req.params;

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const limits = userDb.getUserLimits(id);
    res.json({
      total_limit_usd: limits?.total_limit_usd ?? null,
      daily_limit_usd: limits?.daily_limit_usd ?? null
    });
  } catch (error) {
    console.error('Error fetching user limits:', error);
    res.status(500).json({ error: '获取用户限制失败' });
  }
});

// Update user spending limits
router.patch('/users/:id/limits', (req, res) => {
  try {
    const { id } = req.params;
    const { total_limit_usd, daily_limit_usd } = req.body;

    // Validate limits - allow null or positive numbers
    if (total_limit_usd !== null && total_limit_usd !== undefined) {
      if (typeof total_limit_usd !== 'number' || total_limit_usd < 0) {
        return res.status(400).json({ error: '总额度限制必须是正数或为空' });
      }
    }
    if (daily_limit_usd !== null && daily_limit_usd !== undefined) {
      if (typeof daily_limit_usd !== 'number' || daily_limit_usd < 0) {
        return res.status(400).json({ error: '每日额度限制必须是正数或为空' });
      }
    }

    const isSelf = parseInt(id) === req.user.id;

    // admin can only set limits for themselves or for user-role accounts
    if (req.user.role === 'admin' && !isSelf) {
      const targetUser = userDb.getUserById(id);
      if (!targetUser) {
        return res.status(404).json({ error: 'User not found' });
      }
      if (['admin', 'super_admin'].includes(targetUser.role)) {
        return res.status(403).json({ error: '无权修改管理员账户的限额' });
      }
    }

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // Convert undefined to null for database
    const totalLimit = total_limit_usd === undefined ? null : total_limit_usd;
    const dailyLimit = daily_limit_usd === undefined ? null : daily_limit_usd;

    userDb.updateUserLimits(id, totalLimit, dailyLimit);
    res.json({
      success: true,
      message: '用户额度限制已更新',
      limits: {
        total_limit_usd: totalLimit,
        daily_limit_usd: dailyLimit
      }
    });
  } catch (error) {
    console.error('Error updating user limits:', error);
    res.status(500).json({ error: '更新用户限制失败' });
  }
});

// ==================== Email Domain Whitelist ====================

// Get all whitelisted domains
router.get('/email-domains', (req, res) => {
  try {
    const domains = domainWhitelistDb.getAllDomains();
    res.json({ domains });
  } catch (error) {
    console.error('Error fetching email domains:', error);
    res.status(500).json({ error: '获取域名列表失败' });
  }
});

// Add a domain to whitelist
router.post('/email-domains', (req, res) => {
  try {
    const { domain } = req.body;

    if (!domain) {
      return res.status(400).json({ error: '域名不能为空' });
    }

    // Validate domain format
    const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}$/;
    if (!domainRegex.test(domain)) {
      return res.status(400).json({ error: '域名格式无效' });
    }

    const result = domainWhitelistDb.addDomain(domain, req.user.id);
    res.json({ success: true, domain: result });
  } catch (error) {
    console.error('Error adding email domain:', error);
    if (error.message === '域名已存在') {
      res.status(409).json({ error: error.message });
    } else {
      res.status(500).json({ error: '添加域名失败' });
    }
  }
});

// Remove a domain from whitelist
router.delete('/email-domains/:id', (req, res) => {
  try {
    const { id } = req.params;
    const success = domainWhitelistDb.removeDomain(parseInt(id));

    if (success) {
      res.json({ success: true, message: '域名已删除' });
    } else {
      res.status(404).json({ error: '域名不存在' });
    }
  } catch (error) {
    console.error('Error removing email domain:', error);
    res.status(500).json({ error: '删除域名失败' });
  }
});

// ==================== System Settings ====================

// Get default spending limits for new users
router.get('/settings/default-limits', (req, res) => {
  try {
    const defaultTotalLimit = settingsDb.get('default_total_limit_usd');
    const defaultDailyLimit = settingsDb.get('default_daily_limit_usd');
    res.json({
      default_total_limit_usd: defaultTotalLimit !== null ? parseFloat(defaultTotalLimit) : null,
      default_daily_limit_usd: defaultDailyLimit !== null ? parseFloat(defaultDailyLimit) : null,
    });
  } catch (error) {
    console.error('Error fetching default limits:', error);
    res.status(500).json({ error: '获取默认限额设置失败' });
  }
});

// Update default spending limits for new users
router.put('/settings/default-limits', (req, res) => {
  try {
    const { default_total_limit_usd, default_daily_limit_usd } = req.body;

    if (default_total_limit_usd !== null && default_total_limit_usd !== undefined) {
      if (typeof default_total_limit_usd !== 'number' || default_total_limit_usd < 0) {
        return res.status(400).json({ error: '默认总额度限制必须是正数或为空' });
      }
    }

    if (default_daily_limit_usd !== null && default_daily_limit_usd !== undefined) {
      if (typeof default_daily_limit_usd !== 'number' || default_daily_limit_usd < 0) {
        return res.status(400).json({ error: '默认日限制必须是正数或为空' });
      }
    }

    if (default_total_limit_usd === null || default_total_limit_usd === undefined) {
      settingsDb.delete('default_total_limit_usd');
    } else {
      settingsDb.set('default_total_limit_usd', String(default_total_limit_usd), req.user.id);
    }

    if (default_daily_limit_usd === null || default_daily_limit_usd === undefined) {
      settingsDb.delete('default_daily_limit_usd');
    } else {
      settingsDb.set('default_daily_limit_usd', String(default_daily_limit_usd), req.user.id);
    }

    res.json({
      success: true,
      message: '默认限额已更新',
      default_total_limit_usd: default_total_limit_usd ?? null,
      default_daily_limit_usd: default_daily_limit_usd ?? null,
    });
  } catch (error) {
    console.error('Error updating default limits:', error);
    res.status(500).json({ error: '更新默认限额设置失败' });
  }
});

// ==================== Feature Permissions ====================

// Get user feature permissions (raw, not resolved)
router.get('/users/:id/permissions', (req, res) => {
  try {
    const { id } = req.params;

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const raw = userDb.getFeaturePermissions(id);
    let permissions = null;
    if (raw) {
      try { permissions = JSON.parse(raw); } catch (_) { /* ignore */ }
    }

    res.json({ permissions });
  } catch (error) {
    console.error('Error fetching user permissions:', error);
    res.status(500).json({ error: '获取用户权限失败' });
  }
});

// Update user feature permissions
router.patch('/users/:id/permissions', (req, res) => {
  try {
    const { id } = req.params;
    const { permissions } = req.body;

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // admin / super_admin 免检，不应设置权限
    if (['admin', 'super_admin'].includes(user.role)) {
      return res.status(400).json({ error: '管理员始终拥有全部权限，无需配置' });
    }

    // admin 不能操作 admin/super_admin
    if (req.user.role === 'admin' && ['admin', 'super_admin'].includes(user.role)) {
      return res.status(403).json({ error: '无权修改管理员的权限' });
    }

    // permissions 为 null 表示重置为默认
    if (permissions === null) {
      userDb.updateFeaturePermissions(parseInt(id), null);
      return res.json({ success: true, message: '用户权限已重置为默认' });
    }

    // 校验 permissions 对象
    if (typeof permissions !== 'object' || Array.isArray(permissions)) {
      return res.status(400).json({ error: '权限格式无效' });
    }

    // 只允许已知的权限 key
    const validKeys = Object.keys(ALL_FEATURE_PERMISSIONS);
    const filtered = {};
    for (const key of validKeys) {
      if (key in permissions) {
        filtered[key] = !!permissions[key];
      }
    }

    userDb.updateFeaturePermissions(parseInt(id), filtered);
    res.json({ success: true, message: '用户权限已更新', permissions: filtered });
  } catch (error) {
    console.error('Error updating user permissions:', error);
    res.status(500).json({ error: '更新用户权限失败' });
  }
});

// Get default feature permissions
router.get('/settings/default-permissions', (req, res) => {
  try {
    const permissions = getDefaultPermissions();
    // 同时返回 DB 中存储的原始值，以便前端区分是否已设置
    const raw = settingsDb.get('default_feature_permissions');
    res.json({ permissions, hasCustom: raw !== null });
  } catch (error) {
    console.error('Error fetching default permissions:', error);
    res.status(500).json({ error: '获取默认权限设置失败' });
  }
});

// Update default feature permissions
router.put('/settings/default-permissions', (req, res) => {
  try {
    const { permissions } = req.body;

    // permissions 为 null 表示清除自定义，回退到环境变量/硬编码
    if (permissions === null) {
      settingsDb.delete('default_feature_permissions');
      return res.json({ success: true, message: '默认权限已重置', permissions: getDefaultPermissions() });
    }

    if (typeof permissions !== 'object' || Array.isArray(permissions)) {
      return res.status(400).json({ error: '权限格式无效' });
    }

    // 只允许已知的权限 key
    const validKeys = Object.keys(ALL_FEATURE_PERMISSIONS);
    const filtered = {};
    for (const key of validKeys) {
      if (key in permissions) {
        filtered[key] = !!permissions[key];
      }
    }

    settingsDb.set('default_feature_permissions', JSON.stringify(filtered), req.user.id);
    res.json({ success: true, message: '默认权限已更新', permissions: { ...ALL_FEATURE_PERMISSIONS, ...filtered } });
  } catch (error) {
    console.error('Error updating default permissions:', error);
    res.status(500).json({ error: '更新默认权限设置失败' });
  }
});

// ─── Agent Visibility ───────────────────────────────────────────────────────

// GET /api/admin/users/:id/visible-agents - Get user's visible agents config
router.get('/users/:id/visible-agents', (req, res) => {
  try {
    const { id } = req.params;
    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const raw = userDb.getVisibleAgents(id);
    let agents = null;
    if (raw) {
      try { agents = JSON.parse(raw); } catch (_) { /* ignore */ }
    }

    res.json({ agents });
  } catch (error) {
    console.error('Error getting user visible agents:', error);
    res.status(500).json({ error: '获取用户 Agent 可见性失败' });
  }
});

// PATCH /api/admin/users/:id/visible-agents - Update user's visible agents
router.patch('/users/:id/visible-agents', (req, res) => {
  try {
    const { id } = req.params;
    const { agents } = req.body;

    const user = userDb.getUserById(id);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    // admin/super_admin always see all agents, no need to configure
    if (['admin', 'super_admin'].includes(user.role)) {
      return res.status(400).json({ error: '管理员始终可见全部 Agent，无需配置' });
    }

    // admin cannot modify admin/super_admin
    if (req.user.role === 'admin' && ['admin', 'super_admin'].includes(user.role)) {
      return res.status(403).json({ error: '无权修改管理员的 Agent 可见性' });
    }

    // null = reset to default (no agents visible)
    if (agents === null) {
      userDb.updateVisibleAgents(parseInt(id), null);
      return res.json({ success: true, message: 'Agent 可见性已重置为默认' });
    }

    // Validate agents is an array
    if (!Array.isArray(agents)) {
      return res.status(400).json({ error: 'agents 必须是数组' });
    }

    // Only allow non-empty strings
    const filtered = agents.filter(a => typeof a === 'string' && a.length > 0);

    userDb.updateVisibleAgents(parseInt(id), filtered);
    res.json({ success: true, message: 'Agent 可见性已更新', agents: filtered });
  } catch (error) {
    console.error('Error updating user visible agents:', error);
    res.status(500).json({ error: '更新用户 Agent 可见性失败' });
  }
});

export default router;
