import mysql, { ResultSetHeader, RowDataPacket } from "mysql2";
import DB from "../config/database/db";
import clientConfigTypes from "../schemas/clientConfig.schema";
import log from "../config/log";

const clientConfigDB: any = {};

clientConfigDB.getClientConfig = async ({
  clientId,
  provider,
  type
}: clientConfigTypes) => {
  const query =
    "Select * from ClientConfig where clientId = ? and provider=? and type=? and propId IS NULL";
  const data = [clientId, provider, type];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};

clientConfigDB.getClientConfigByPropId = async ({
  clientId,
  propId,
  provider,
  type
}: clientConfigTypes) => {
  const query =
    "Select * from ClientConfig where clientId = ? and propId =? and provider=? and type=? and propId IS NOT NULL";
  const data = [clientId, propId, provider, type];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};

clientConfigDB.create = async ({ clientId, provider, type, value, propId=null}: clientConfigTypes) => {
  const query = `INSERT INTO ClientConfig ( clientId, propId, provider, type, value) VALUES (?, ?, ?, ?, ?)`;
  const data = [clientId, propId, provider, type, value];
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};

clientConfigDB.update = async ({ clientId, provider, type, value, propId}: clientConfigTypes) => {
  let query = `UPDATE ClientConfig set value=? where clientId=? and provider=? and type=?`;
  let data = [value, clientId, provider, type];
  if(propId){
    query += ` and propId=?`;
    data.push(propId);
  }else{
    query += ` and propId IS NULL`;
  }
  query += ` limit 1`;
  await DB.execute<ResultSetHeader[]>(query, data);
  return true;
};


export default clientConfigDB;
