const pool = require("../config");

// Get all tags
const getAllTagsDb = async (searchParams = {}) => {
  let queryParams = [];

  if (searchParams.limit) {
    const page = Number(searchParams.page ?? 1) - 1;
    queryParams = [Number(searchParams.limit ?? 10), page];
  }

  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    [
      "a.tag_name",
      "a.tag_code",
      "a.tag_number",
      "a.data_type",
      "a.unit",
      "b.device_name",
      "c.plant_sub_section_name",
    ],
    searchParams.criteria,
    queryParams
  );

  if (whereParamOr) queryParams = whereParamOr;

  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "a.tag_name", param: searchParams.name, type: "string" },
      { column: "a.tag_code", param: searchParams.code, type: "string" },
      { column: "a.data_type", param: searchParams.data, type: "string" },
      { column: "a.unit", param: searchParams.unit, type: "string" },
      { column: "b.device_name", param: searchParams.device, type: "string" },
      {
        column: "b.device_code",
        param: searchParams.device,
        type: "string",
      },
      {
        column: "c.plant_sub_section_name",
        param: searchParams.subsection,
        type: "string",
      },
    ],
    queryParams
  );

  if (whereParamAnd) queryParams = whereParamAnd;

  const queryText = `
    SELECT 
      COUNT(*) OVER() AS total_data, 
      a.*, 
      b.device_name, 
      b.device_code,
      c.plant_sub_section_name
    FROM m_tags a
    LEFT JOIN m_device b ON a.device_id = b.device_id
    LEFT JOIN m_plant_sub_section c ON a.plant_sub_section_id = c.plant_sub_section_id
    WHERE a.deleted_at IS NULL
      ${whereConditions.length > 0 ? ` AND ${whereConditions.join(" AND ")}` : ""}
      ${whereOrConditions ? ` ${whereOrConditions}` : ""}
    ORDER BY a.tag_id ASC
     ${searchParams.limit ? `OFFSET $2 * $1 ROWS FETCH NEXT $1 ROWS ONLY` : ''}
  `;

  const result = await pool.query(queryText, queryParams);

  const total =
    result?.recordset?.length > 0
      ? parseInt(result.recordset[0].total_data, 10)
      : 0;

  return { data: result.recordset, total };
};

const getTagsByIdDb = async (id) => {
  const queryText = `
    SELECT 
      a.*, 
      b.device_name, 
      b.device_code,
      c.plant_sub_section_name
    FROM m_tags a
    LEFT JOIN m_device b ON a.device_id = b.device_id
    LEFT JOIN m_plant_sub_section c ON a.plant_sub_section_id = c.plant_sub_section_id
    WHERE a.tag_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset;
};

const createTagsDb = async (data) => {
  const newCode = await pool.generateKode("TAG", "m_tags", "tag_code");

  const store = {
    ...data,
    tag_code: newCode,
  };

  const { query: queryText, values } = pool.buildDynamicInsert("m_tags", store);
  const result = await pool.query(queryText, values);
  const insertedId = result.recordset[0]?.inserted_id;

  return insertedId ? await getTagsByIdDb(insertedId) : null;
};

const updateTagsDb = async (id, data) => {
  const store = { ...data };
  const whereData = { tag_id: id };

  const { query: queryText, values } = pool.buildDynamicUpdate(
    "m_tags",
    store,
    whereData
  );

  await pool.query(`${queryText} AND deleted_at IS NULL`, values);
  return getTagsByIdDb(id); 
};

// Soft delete tag
const deleteTagsDb = async (id, deletedBy) => {
  const queryText = `
    UPDATE m_tags
    SET deleted_at = CURRENT_TIMESTAMP, deleted_by = $1
    WHERE tag_id = $2 AND deleted_at IS NULL
  `;
  await pool.query(queryText, [deletedBy, id]);
  return true;
};

module.exports = {
  getAllTagsDb,
  getTagsByIdDb,
  createTagsDb,
  updateTagsDb,
  deleteTagsDb,
};
