import { ResultSetHeader, RowDataPacket } from "mysql2";
import DB from "../config/database/db";
import log from "../config/log";
import CONSTANTS from "../config/constants";
import wifiCredentialTypes from "../schemas/wifiCredentials.schema";

const wifiCredentialsDB: any = {};

wifiCredentialsDB.add = async ({
  clientId,
  tenantId,
  title,
  device,
  password,
}: wifiCredentialTypes) => {
  const query =
    "Insert into WifiCredentials (clientId, tenantId, title, password, device) values (?, ?, ?, ?, ?)";
  const data = [clientId, tenantId, title, password, device];
  const [rows] = await DB.query<ResultSetHeader>(query, data);
  return rows.insertId;
};

wifiCredentialsDB.edit = async ({
  id,
  title,
  password,
  device,
}: wifiCredentialTypes) => {
  const query = "Update WifiCredentials set title = ?, password = ?, device = ? where id = ?";
  const data = [title, password, device, id];
  const [rows] = await DB.execute<ResultSetHeader>(query, data);
  if (rows.affectedRows > 0) return true;
  else return false;
};

wifiCredentialsDB.delete = async ({
  id,
}: wifiCredentialTypes) => {
  const query = "Delete * from WifiCredentials where id = ?";
  const data = [id];
  const [rows] = await DB.execute<ResultSetHeader>(query, data);
  return true;
};

wifiCredentialsDB.getById = async ({ id }: wifiCredentialTypes) => {
  const query = "Select * from WifiCredentials where id = ?";
  const data = [id];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};

wifiCredentialsDB.getByTenantIdAndClientId = async ({ tenantId, clientId }: wifiCredentialTypes) => {
  const query = "Select * from WifiCredentials where clientId = ? and tenantId = ?";
  const data = [clientId, tenantId];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows;
  else return false;
};



export default wifiCredentialsDB;