/**
 * 职位类型管理API - 后台管理
 * 提供职位类型的查询和管理功能
 */

const Framework = require("../../framework/node-core-framework.js");

module.exports = {
  /**
   * @swagger
   * /admin_api/job_type/list:
   *   post:
   *     summary: 获取职位类型列表
   *     description: 分页获取所有职位类型
   *     tags: [后台-职位类型管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             properties:
   *               page:
   *                 type: integer
   *                 description: 页码
   *               pageSize:
   *                 type: integer
   *                 description: 每页数量
   *               name:
   *                 type: string
   *                 description: 职位类型名称（可选）
   *     responses:
   *       200:
   *         description: 获取成功
   */
  'POST /job_type/list': async (ctx) => {
    const models = Framework.getModels();
    const { job_types, op } = models;
    const body = ctx.getBody();
    const { name } = body;

    // 获取分页参数
    const { limit, offset } = ctx.getPageSize();

    const where = {};
    if (name) {
      where.name = { [op.like]: `%${name}%` };
    }

    const result = await job_types.findAndCountAll({
      where,
      limit,
      offset,
      order: [['sort_order', 'ASC'], ['id', 'ASC']]
    });

    return ctx.success(result);
  },

  /**
   * @swagger
   * /admin_api/job_type/detail:
   *   get:
   *     summary: 获取职位类型详情
   *     description: 根据ID获取职位类型详细信息
   *     tags: [后台-职位类型管理]
   *     parameters:
   *       - in: query
   *         name: id
   *         required: true
   *         schema:
   *           type: integer
   *         description: 职位类型ID
   *     responses:
   *       200:
   *         description: 获取成功
   */
  'GET /job_type/detail': async (ctx) => {
    const models = Framework.getModels();
    const { job_types } = models;
    const { id } = ctx.getQuery();

    if (!id) {
      return ctx.fail('职位类型ID不能为空');
    }

    const jobType = await job_types.findByPk(id);
    if (!jobType) {
      return ctx.fail('职位类型不存在');
    }

    return ctx.success(jobType);
  },

  /**
   * @swagger
   * /admin_api/job_type/create:
   *   post:
   *     summary: 创建职位类型
   *     description: 创建新的职位类型
   *     tags: [后台-职位类型管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - name
   *             properties:
   *               name:
   *                 type: string
   *                 description: 职位类型名称
   *               description:
   *                 type: string
   *                 description: 职位类型描述
   *               commonSkills:
   *                 type: array
   *                 description: 常见技能关键词（JSON数组）
   *               excludeKeywords:
   *                 type: array
   *                 description: 排除关键词（JSON数组）
   *               is_enabled:
   *                 type: integer
   *                 description: 是否启用（1=启用，0=禁用）
   *               sort_order:
   *                 type: integer
   *                 description: 排序顺序
   *     responses:
   *       200:
   *         description: 创建成功
   */
  'POST /job_type/create': async (ctx) => {
    const models = Framework.getModels();
    const { job_types } = models;
    const body = ctx.getBody();
    const { name, description, commonSkills, excludeKeywords, is_enabled, sort_order } = body;

    if (!name) {
      return ctx.fail('职位类型名称不能为空');
    }

    // 检查名称是否已存在
    const existing = await job_types.findOne({ where: { name } });
    if (existing) {
      return ctx.fail('职位类型名称已存在');
    }

    const jobType = await job_types.create({
      name,
      description: description || '',
      commonSkills: Array.isArray(commonSkills) ? JSON.stringify(commonSkills) : (commonSkills || '[]'),
      excludeKeywords: Array.isArray(excludeKeywords) ? JSON.stringify(excludeKeywords) : (excludeKeywords || '[]'),
      is_enabled: is_enabled !== undefined ? is_enabled : 1,
      sort_order: sort_order || 0
    });

    return ctx.success(jobType);
  },

  /**
   * @swagger
   * /admin_api/job_type/update:
   *   post:
   *     summary: 更新职位类型
   *     description: 更新职位类型信息
   *     tags: [后台-职位类型管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - id
   *             properties:
   *               id:
   *                 type: integer
   *                 description: 职位类型ID
   *               name:
   *                 type: string
   *                 description: 职位类型名称
   *               description:
   *                 type: string
   *                 description: 职位类型描述
   *               commonSkills:
   *                 type: array
   *                 description: 常见技能关键词（JSON数组）
   *               excludeKeywords:
   *                 type: array
   *                 description: 排除关键词（JSON数组）
   *               is_enabled:
   *                 type: integer
   *                 description: 是否启用（1=启用，0=禁用）
   *               sort_order:
   *                 type: integer
   *                 description: 排序顺序
   *     responses:
   *       200:
   *         description: 更新成功
   */
  'POST /job_type/update': async (ctx) => {
    const models = Framework.getModels();
    const { job_types } = models;
    const body = ctx.getBody();
    const { id, name, description, commonSkills, excludeKeywords, is_enabled, sort_order } = body;

    if (!id) {
      return ctx.fail('职位类型ID不能为空');
    }

    const jobType = await job_types.findByPk(id);
    if (!jobType) {
      return ctx.fail('职位类型不存在');
    }

    // 如果更新名称，检查是否与其他记录冲突
    if (name && name !== jobType.name) {
      const existing = await job_types.findOne({ where: { name } });
      if (existing) {
        return ctx.fail('职位类型名称已存在');
      }
    }

    const updateData = {};
    if (name !== undefined) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    if (commonSkills !== undefined) {
      updateData.commonSkills = Array.isArray(commonSkills) ? JSON.stringify(commonSkills) : commonSkills;
    }
    if (excludeKeywords !== undefined) {
      updateData.excludeKeywords = Array.isArray(excludeKeywords) ? JSON.stringify(excludeKeywords) : excludeKeywords;
    }
    if (is_enabled !== undefined) updateData.is_enabled = is_enabled;
    if (sort_order !== undefined) updateData.sort_order = sort_order;

    await job_types.update(updateData, { where: { id } });

    // 清除缓存
    const jobFilterService = require('../middleware/job/job_filter_service.js');
    jobFilterService.clearCache(id);

    return ctx.success({ message: '职位类型更新成功' });
  },

  /**
   * @swagger
   * /admin_api/job_type/delete:
   *   post:
   *     summary: 删除职位类型
   *     description: 删除指定的职位类型
   *     tags: [后台-职位类型管理]
   *     requestBody:
   *       required: true
   *       content:
   *         application/json:
   *           schema:
   *             type: object
   *             required:
   *               - id
   *             properties:
   *               id:
   *                 type: integer
   *                 description: 职位类型ID
   *     responses:
   *       200:
   *         description: 删除成功
   */
  'POST /job_type/delete': async (ctx) => {
    const models = Framework.getModels();
    const { job_types, pla_account } = models;
    const { id } = ctx.getBody();

    if (!id) {
      return ctx.fail('职位类型ID不能为空');
    }

    const jobType = await job_types.findByPk(id);
    if (!jobType) {
      return ctx.fail('职位类型不存在');
    }

    // 检查是否有账号使用此职位类型
    const accountsUsing = await pla_account.count({ where: { job_type_id: id } });
    if (accountsUsing > 0) {
      return ctx.fail(`该职位类型正在被 ${accountsUsing} 个账号使用，无法删除`);
    }

    await job_types.destroy({ where: { id } });

    // 清除缓存
    const jobFilterService = require('../middleware/job/job_filter_service.js');
    jobFilterService.clearCache(id);

    return ctx.success({ message: '职位类型删除成功' });
  },

  /**
   * @swagger
   * /admin_api/job_type/all:
   *   get:
   *     summary: 获取所有启用的职位类型（用于下拉选择）
   *     description: 获取所有启用的职位类型列表
   *     tags: [后台-职位类型管理]
   *     responses:
   *       200:
   *         description: 获取成功
   */
  'GET /job_type/all': async (ctx) => {
    const models = Framework.getModels();
    const { job_types } = models;

    const list = await job_types.findAll({
      where: { is_enabled: 1 },
      order: [['sort_order', 'ASC'], ['id', 'ASC']],
      attributes: ['id', 'name', 'description']
    });

    return ctx.success(list);
  }
};

