import DB from "../config/database/db";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import sosAlertTypes from "../schemas/sosAlert.schema";

const sosAlertDB: any = {};

sosAlertDB.getById = async ({ id }: sosAlertTypes) => {
  const query = "SELECT * FROM SOSAlert WHERE id = ?";
  const [rows] = await DB.execute<RowDataPacket[]>(query, [id]);

  if (rows?.length > 0) return rows[0];
  return false;
};

sosAlertDB.getByTenantId = async ({ tenantId }: sosAlertTypes) => {
  const query =
    "SELECT * FROM SOSAlert WHERE tenantId = ? ORDER BY id DESC";

  const [rows] = await DB.execute<RowDataPacket[]>(query, [tenantId]);

  if (rows?.length > 0) return rows;
  return false;
};

sosAlertDB.getOpenByPropertyId = async ({ propId }: sosAlertTypes) => {
  const query =
    "SELECT * FROM SOSAlert WHERE propId = ? AND status = 1 ORDER BY id DESC";

  const [rows] = await DB.execute<RowDataPacket[]>(query, [propId]);

  if (rows?.length > 0) return rows;
  return false;
};

sosAlertDB.getByClientId = async ({ clientId }: sosAlertTypes) => {
  const query =
    "SELECT * FROM SOSAlert WHERE clientId = ? ORDER BY id DESC";

  const [rows] = await DB.execute<RowDataPacket[]>(query, [clientId]);

  if (rows?.length > 0) return rows;
  return false;
};

sosAlertDB.add = async ({tenantId, clientId, propId, roomId}: sosAlertTypes) => {
  const query = `INSERT INTO SOSAlert (tenantId, clientId, propId, roomId) VALUES (?, ?, ?, ?)`;

  const data = [tenantId, clientId, propId, roomId];

  const [rows] = await DB.query<ResultSetHeader>(query, data);

  return rows.insertId;
};

sosAlertDB.acknowledgeSOS = async ({id, acknowledgedBy}: sosAlertTypes) => {
  const query = `UPDATE SOSAlert SET status = 2, acknowledgedBy = ?, acknowledgedAt = NOW() WHERE id = ?`;

  await DB.query<ResultSetHeader>(query, [acknowledgedBy, id]);

  return true;
};

sosAlertDB.resolveSOS = async ({id, resolvedBy}: sosAlertTypes) => {
  const query = `
    UPDATE SOSAlert SET status = 3, resolvedBy = ?, resolvedAt = NOW() WHERE id = ?`;

  await DB.query<ResultSetHeader>(query, [resolvedBy, id]);

  return true;
};

export default sosAlertDB;