/**
 * Admin category service
 */

const Category = require('../models/Category');

/**
 * Get all categories
 */
exports.getAllCategories = async () => {
  const categories = await Category.findAll({
    order: [
      ['sort_order', 'ASC'],
      ['created_at', 'ASC'],
    ],
  });
  return categories;
};

/**
 * Get category by ID
 */
exports.getCategoryById = async (id) => {
  const category = await Category.findByPk(id);
  if (!category) {
    throw new Error('Category not found');
  }
  return category;
};

/**
 * Create category
 */
exports.createCategory = async (data) => {
  const { key, name_zh, name_en, name_pt, icon, sort_order } = data;

  if (!key || !name_zh || !name_en || !name_pt) {
    throw new Error('All language names and key are required');
  }

  // Check if key already exists
  const existing = await Category.findOne({ where: { key } });
  if (existing) {
    throw new Error('Category key already exists');
  }

  const category = await Category.create({
    key,
    name_zh,
    name_en,
    name_pt,
    icon: icon || null,
    sort_order: sort_order || 0,
  });

  return category;
};

/**
 * Update category
 */
exports.updateCategory = async (id, data) => {
  const category = await Category.findByPk(id);

  if (!category) {
    throw new Error('Category not found');
  }

  const { key, name_zh, name_en, name_pt, icon, sort_order } = data;

  // Check if key already exists (excluding current category)
  if (key && key !== category.key) {
    const existing = await Category.findOne({ where: { key } });
    if (existing) {
      throw new Error('Category key already exists');
    }
  }

  await category.update({
    key: key || category.key,
    name_zh: name_zh || category.name_zh,
    name_en: name_en || category.name_en,
    name_pt: name_pt || category.name_pt,
    icon: icon !== undefined ? icon : category.icon,
    sort_order: sort_order !== undefined ? sort_order : category.sort_order,
  });

  return category;
};

/**
 * Delete category
 */
exports.deleteCategory = async (id) => {
  const category = await Category.findByPk(id);

  if (!category) {
    throw new Error('Category not found');
  }

  await category.destroy();
};
