import DB from "../config/database/db";
import { ResultSetHeader, RowDataPacket } from "mysql2";
import requestTypes from "../schemas/request.schema";
import moveInTypes from "../schemas/moveIn.schema";

const moveInDB: any = {};

moveInDB.getByTenantIdandClientId = async ({
  tenantId,
  clientId,
}: moveInTypes) => {
  const query =
    "Select * from MoveInInspections where tenantId = ? and clientId =?";
  const data = [tenantId, clientId];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};
moveInDB.getMovinDetails = async ({
  tenantId,
  clientId,
  typeId,
}: moveInTypes) => {
  const query =
    "Select * from MoveInInspections where tenantId = ? and clientId =? and typeId = ?";
  const data = [tenantId, clientId, typeId];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows[0];
  else return false;
};

moveInDB.getTypeList = async ({ propId, clientId, tenantId }: moveInTypes) => {
  //const query =
    //"Select T.name, T.id from MoveInInspectionTypeList as T inner join SelectedMoveInInspectionTypes as ST on ST.typeId = T.id where ST.propId = ? and ST.clientId =?";
  const query = 
	  "Select T.name, T.id, if((select id from MoveInInspections where MoveInInspections.typeId=T.id and MoveInInspections.tenantId=? and MoveInInspections.clientId=ST.clientId and MoveInInspections.propId=ST.propId) IS NULL, false, true) as isDetailAdded from MoveInInspectionTypeList as T inner join SelectedMoveInInspectionTypes as ST on ST.typeId = T.id where ST.propId =?  and ST.clientId =?";
  const data = [tenantId, propId, clientId];
  const [rows] = await DB.execute<RowDataPacket[]>(query, data);
  if (rows?.length > 0) return rows;
  else return false;
};

moveInDB.add = async ({
  tenantId,
  roomId,
  comment,
  propId,
  clientId,
  typeId,
}: moveInTypes) => {
  const query =
    "INSERT INTO MoveInInspections (tenantId, roomId, comment, propId, clientId, typeId) VALUES (?, ?, ?, ?, ?, ?)";
  const data = [tenantId, roomId, comment, propId, clientId, typeId];
  const [rows] = await DB.query<ResultSetHeader>(query, data);
  return rows.insertId;
};

moveInDB.removeById = async ({ id }: moveInTypes) => {
  const query = "Delete from MoveInInspections where id = ?";
  const data = [id];
  const [rows] = await DB.query<ResultSetHeader>(query, data);
  return true;
};

export default moveInDB;
