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

const InsertNotificationErrorDb = async () => {
  const insertQuery = `
    INSERT INTO notification_error (
      error_code_id,
      is_active,
      is_delivered,
      is_read,
      is_send,
      message_error_issue
    )
    SELECT
      b.error_code_id,
      1 AS is_active,
      1 AS is_delivered,
      0 AS is_read,
      1 AS is_send,

      CONCAT(
        COALESCE(b.error_code_description, '-'),
        ' pada ',
        COALESCE(d.device_name, '-'),
        '. Pengecekan potensi kerusakan dibutuhkan'
      ) AS message_error_issue

    FROM brand_code b

    LEFT JOIN notification_error a
      ON a.error_code_id = b.error_code_id
     AND a.deleted_at IS NULL

    LEFT JOIN m_device d 
     ON b.brand_id = d.brand_id
     AND d.deleted_at IS NULL

    WHERE b.deleted_at IS NULL
      AND a.notification_error_id IS NULL;
  `;

  await pool.query(insertQuery);
};

const getNotificationByIdDb = async (id) => {
  const queryText = `
    SELECT
      a.*
    FROM notification_error a
    WHERE a.notification_error_id = $1 AND a.deleted_at IS NULL
  `;
  const result = await pool.query(queryText, [id]);
  return result.recordset[0];
};

const getAllNotificationDb = async (searchParams = {}) => {
  let queryParams = [];

  await InsertNotificationErrorDb();

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

  // Build dynamic WHERE OR
  const { whereOrConditions, whereParamOr } = pool.buildStringOrIlike(
    [
      "b.error_code",
      "b.error_code_name",
      "c.solution_name",
      "COALESCE(a.is_send, 0)",
      "COALESCE(a.is_delivered, 0)",
      "COALESCE(a.is_read, 0)",
      "COALESCE(a.is_active, 0)"
    ],
    searchParams.criteria,
    queryParams
  );
  if (whereParamOr) queryParams = whereParamOr;

  // Build dynamic WHERE AND
  const { whereConditions, whereParamAnd } = pool.buildFilterQuery(
    [
      { column: "COALESCE(a.is_send, 0)", param: searchParams.is_send, type: "int" },
      { column: "COALESCE(a.is_delivered, 0)", param: searchParams.is_delivered, type: "int" },
      { column: "COALESCE(a.is_read, 0)", param: searchParams.is_read, type: "int" },
      { column: "COALESCE(a.is_active, 0)", param: searchParams.is_active, type: "int" },
    ],
    queryParams
  );
  if (whereParamAnd) queryParams = whereParamAnd;


  const queryText = `
    SELECT
      COUNT(*) OVER() AS total_data,

      a.notification_error_id,
      a.error_code_id,
      a.message_error_issue,
      a.is_send,
      a.is_delivered,
      a.is_read,
      a.is_active,

      b.error_code,
      b.error_code_name,
      b.created_at,

      c.solution_name,
      c.type_solution,
      c.path_solution,

      d.device_name,
      d.device_location,

      COALESCE(d.device_name, '') + ' - ' + COALESCE(b.error_code_name, '') AS device_name_error

    FROM notification_error a
    
    LEFT JOIN brand_code b
      ON a.error_code_id = b.error_code_id
      AND b.deleted_at IS NULL

    LEFT JOIN brand_code_solution c
      ON b.error_code_id = c.error_code_id
      AND c.deleted_at IS NULL

    LEFT JOIN m_device d
      ON b.brand_id = d.brand_id
      AND d.deleted_at IS NULL

    WHERE a.deleted_at IS NULL
      ${
        whereConditions.length > 0
          ? ` AND ${whereConditions.join(" AND ")}`
          : ""
      }
      ${whereOrConditions ? ` ${whereOrConditions}` : ""}

    ORDER BY a.notification_error_id DESC

    ${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 };
};

module.exports = {
  getNotificationByIdDb,
  getAllNotificationDb,
};
