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

exports.createIssueType = async (req, res) => {
  try {
    const id = await new Promise((resolve, reject) => {
      issueTypeModel.create(req.body, (err, insertId) =>
        err ? reject(err) : resolve(insertId)
      );
    });
    res.json({ success: true, issue_type_id: id });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

exports.getAllIssueTypes = async (_req, res) => {
  try {
    const rows = await new Promise((resolve, reject) => {
      issueTypeModel.getAll((err, data) => err ? reject(err) : resolve(data));
    });
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

exports.updateIssueType = async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    const changes = await new Promise((resolve, reject) => {
      issueTypeModel.update(id, req.body, (err, affectedRows) =>
        err ? reject(err) : resolve(affectedRows)
      );
    });
    if (changes === 0) return res.status(404).json({ error: 'Not found or no changes' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};

exports.removeIssueType = async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    const changes = await new Promise((resolve, reject) => {
      issueTypeModel.remove(id, (err, affectedRows) =>
        err ? reject(err) : resolve(affectedRows)
      );
    });
    if (changes === 0) return res.status(404).json({ error: 'Not found' });
    res.json({ success: true, changes });
  } catch (err) {
    res.status(500).json({ error: err.message || String(err) });
  }
};