// 管理员控制器
const Admin = require('../../models/admin');
const AdminService = require('../../services/admin');
const jwt = require('jsonwebtoken');
const { query } = require('../../config/database');

// 生成JWT token
const generateToken = (admin) => {
  return jwt.sign(
    { id: admin.id, username: admin.username, role: admin.role },
    process.env.JWT_SECRET || 'admin-secret-key',
    { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
  );
};

// 管理员登录
exports.login = async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户名和密码不能为空'
      });
    }

    // 查找管理员
    const admin = await Admin.findByUsername(username);
    if (!admin) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户名或密码错误'
      });
    }

    // 验证密码
    const isPasswordValid = await admin.verifyPassword(password);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户名或密码错误'
      });
    }

    // 更新最后登录时间
    await admin.updateLastLogin();

    // 生成token
    const token = generateToken(admin);

    res.status(200).json({
      success: true,
      code: 200,
      message: '登录成功',
      data: {
        admin: admin.toSafeObject(),
        token
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取当前管理员信息
exports.getProfile = async (req, res, next) => {
  try {
    const admin = await Admin.findById(req.admin.id);
    if (!admin) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }

    res.status(200).json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        admin: admin.toSafeObject()
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取管理员列表
exports.getList = async (req, res, next) => {
  try {
    const result = await AdminService.getAdminList(req.query);

    res.status(200).json({
      success: true,
      code: 200,
      message: '获取成功',
      data: result
    });
  } catch (error) {
    next(error);
  }
};

// 创建管理员
exports.create = async (req, res, next) => {
  try {
    const { username, password, email, nickname, role } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户名和密码不能为空'
      });
    }

    // 创建管理员
    const adminData = {
      username,
      password,
      email: email || null,
      nickname: nickname || null,
      role: role || 'admin',
      status: 1
    };

    const admin = await AdminService.createAdmin(adminData);

    res.status(201).json({
      success: true,
      code: 201,
      message: '创建成功',
      data: {
        admin
      }
    });
  } catch (error) {
    if (error.message === '用户名已存在') {
      return res.status(409).json({
        success: false,
        code: 409,
        message: '用户名已存在'
      });
    }
    next(error);
  }
};

// 更新管理员
exports.update = async (req, res, next) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 不能修改自己角色
    if (req.admin.id == id && updateData.role) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '不能修改自己的角色'
      });
    }

    const admin = await AdminService.updateAdmin(id, updateData);

    res.status(200).json({
      success: true,
      code: 200,
      message: '更新成功',
      data: {
        admin
      }
    });
  } catch (error) {
    if (error.message === '管理员不存在') {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }
    next(error);
  }
};

// 删除管理员
exports.delete = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 不能删除自己
    if (req.admin.id == id) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '不能删除自己'
      });
    }

    await AdminService.deleteAdmin(id);

    res.status(200).json({
      success: true,
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    if (error.message === '管理员不存在') {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }
    next(error);
  }
};