import { Request, Response } from "express";
import adminService from "../services/adminService";
import jwt from "jsonwebtoken";

const SECRET_KEY = "Fwcyfyl123."; // 生产环境请务必使用环境变量

/**
 * 管理员控制器类，处理与管理员相关的HTTP请求
 */
class AdminController {
  /** 注册新管理员 */
  public async register(req: Request, res: Response): Promise<void> {
    try {
      const { username, password } = req.body;
      const newAdmin = await adminService.registerAdmin({ username, password });
      res.status(201).json(newAdmin);
    } catch (error: any) {
      res.status(400).json({ message: error.message });
    }
  }

  /** 管理员登录 */
  public async login(req: Request, res: Response): Promise<void> {
    try {
      const { username, password } = req.body;
      const admin = await adminService.loginAdmin(username, password);

      // 生成JWT Token
      const token = jwt.sign({ id: admin._id, username: admin.username }, SECRET_KEY, { expiresIn: "1d" });

      res.status(200).json({ message: "Login successful", token });
    } catch (error: any) {
      res.status(401).json({ message: error.message });
    }
  }

  /** 获取所有管理员 */
  public async getAdmins(req: Request, res: Response): Promise<void> {
    try {
      const admins = await adminService.getAdmins();
      res.status(200).json(admins);
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  /** 根据ID获取单个管理员 */
  public async getAdminById(req: Request, res: Response): Promise<void> {
    try {
      const admin = await adminService.getAdminById(req.params.id);
      if (!admin) {
        res.status(404).json({ message: "Admin not found" });
      } else {
        res.status(200).json(admin);
      }
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }

  /** 根据ID更新管理员 */
  public async updateAdmin(req: Request, res: Response): Promise<void> {
    try {
      const updatedAdmin = await adminService.updateAdmin(req.params.id, req.body);
      if (!updatedAdmin) {
        res.status(404).json({ message: "Admin not found" });
      } else {
        res.status(200).json(updatedAdmin);
      }
    } catch (error: any) {
      res.status(400).json({ message: error.message });
    }
  }

  /** 根据ID删除管理员 */
  public async deleteAdmin(req: Request, res: Response): Promise<void> {
    try {
      const deletedAdmin = await adminService.deleteAdmin(req.params.id);
      if (!deletedAdmin) {
        res.status(404).json({ message: "Admin not found" });
      } else {
        res.status(200).json({ message: "Admin deleted successfully" });
      }
    } catch (error: any) {
      res.status(500).json({ message: error.message });
    }
  }
}

export default new AdminController();
