import DB from "../config/database/db";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import bankTypes from "../schemas/bankAccount.schema";
import ipAddressTypes from "../schemas/ipAddress.schema";

const ipAddressDB: any = {};

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

ipAddressDB.getByIP = async ({ ip }: ipAddressTypes) => {
  const query = "Select * from IpAdresses where ip = ? order by id desc";
  const data = [ip];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows;
  else return false;
};

ipAddressDB.getCountByHour = async ({ ip }: ipAddressTypes) => {
  const query =
    "Select COUNT(id) as count from IpAdresses where ip = ? and createdAt > DATE_ADD(now(), INTERVAL -1 HOUR) order by id desc";
  const data = [ip];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0].count;
  else return 0;
};

ipAddressDB.add = async ({ userId, userType, ip, target }: ipAddressTypes) => {
  const query =
    "Insert into IpAdresses (userId,userType,ip,target) values (?,?,?,?)";
  const data = [userId, userType, ip, target];
  const [rows] = await DB.query<ResultSetHeader>(query, data);
  return rows.insertId;
};

export default ipAddressDB;
