import * as adminService from "../service/adminService.js";
import { generateToken } from "../middleware/jwt.js";

export async function login(req, res) {
  try {
    const { username, password } = req.body;
    if (!username || !password) return res.send("缺少参数");
    const user = await adminService.login(username, password);
    const token = generateToken({
      id: user.id,
      username: user.username,
      action_list: user.action_list
    })
    res.suc(token);
  } catch (error) {
    res.err(error.message);
  }
}

export function logout(req, res) {
  res.send("管理员登出");
}

export async function getProductList(req, res) {
  try {
    
    const list = await adminService.getProductList();
    res.suc(list);
  } catch (error) {
    res.err(error.message)
  }
}

export async function getProductDetail(req, res) {
  try {
    const { productId } = req.params;
    const result = await adminService.getProductDetail(productId);
    res.suc(result)
  } catch (error) {
    res.err(error.message);
  }
}

export async function createProduct(req, res) {
  try {
    await adminService.createProduct(req.body);
    res.suc();
  } catch (error) {
    res.err(error.message);
  }
}

export async function updateProduct(req, res) {
  try {
    await adminService.updateProduct(req.body);
    res.suc();
  } catch (error) {
    res.err(error.message);
  }
}

export async function deleteProduct(req, res) {
  try {
    const { productId } = req.params;
    await adminService.deleteProduct(productId)
    res.suc()
  } catch (error) {
    res.err(error.message)
  }
}
