const { getDb } = require('../dbPool');

const create = async (factory, callback) => {
  try {
    const db = await getDb();
    const { factory_name, address, description, map_image_url } = factory;

    const [result] = await db.query(
      `INSERT INTO FactoryInfo
       (factory_name, address, description, map_image_url)
       VALUES (?, ?, ?, ?)`,
      [factory_name, address, description, map_image_url]
    );

    callback(null, result.insertId);
  } catch (err) {
    callback(err);
  }
};

const getAll = async (callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM FactoryInfo ORDER BY factory_id DESC`
    );
    callback(null, rows);
  } catch (err) {
    callback(err);
  }
};

const getById = async (factory_id, callback) => {
  try {
    const db = await getDb();
    const [rows] = await db.query(
      `SELECT * FROM FactoryInfo WHERE factory_id = ?`,
      [factory_id]
    );
    callback(null, rows[0]);
  } catch (err) {
    callback(err);
  }
};

const update = async (factory, callback) => {
  try {
    const db = await getDb();
    const { factory_id, factory_name, address, description, map_image_url } = factory;

    const [result] = await db.query(
      `UPDATE FactoryInfo
       SET factory_name  = ?,
           address       = ?,
           description   = ?,
           map_image_url = ?
       WHERE factory_id = ?`,
      [factory_name, address, description, map_image_url, factory_id]
    );

    callback(null, result.affectedRows);
  } catch (err) {
    callback(new Error(err.message || String(err)));
  }
};

const remove = async (factory_id, callback) => {
  try {
    const db = await getDb();
    const [result] = await db.query(
      `DELETE FROM FactoryInfo WHERE factory_id = ?`,
      [factory_id]
    );
    callback(null, result.affectedRows);
  } catch (err) {
    callback(err);
  }
};

module.exports = {
  create,
  getAll,
  getById,
  update,
  remove
};