import { ManagedTransaction, QueryResult } from "neo4j-driver";
import { Klinika, Pacienti } from "./interfaces";
import { getDriver } from "./neo4j.driver";

export const findPacient = async (pacienti: Pacienti) => {
  const driver = getDriver();
  const session = driver.session();

  try {
    const result: QueryResult = await session.executeRead(
      (tx: ManagedTransaction) => {
        return tx.run(
          `MATCH (p:Pacienti) WHERE p.emer = $emer AND p.mbiemer = $mbiemer AND p.mosha = $mosha
            RETURN p
            `,
          {
            emer: pacienti.emer,
            mbiemer: pacienti.mbiemer,
            mosha: pacienti.mosha,
          }
        );
      }
    );
    await session.close();
    return result;
  } catch (error) {
    console.error(error);
    await session.close();
    return null;
  }
};

export const findKlinika = async (klinika: Klinika) => {
  const driver = getDriver();
  const session = driver.session();
  try {
    const result: QueryResult = await session.executeRead(
      (tx: ManagedTransaction) => {
        return tx.run(
          `OPTIONAL MATCH (k:Klinika) WHERE k.emer = $emer RETURN k IS NOT NULL AS Predicate

            `,
          {
            emer: klinika.emer,
          }
        );
      }
    );
    await session.close();
    return result;
  } catch (error) {
    console.error(error);
    await session.close();
    return null;
  }
};

export const upsertKlinika = async (klinika: Klinika) => {
  const klinikaFromDb = await findKlinika(klinika);
  if (!klinikaFromDb?.records[0].get('Predicate')) {
    const driver = getDriver();
    const session = driver.session();

    try {
      const result: QueryResult = await session.run(
        `MERGE (k:Klinika {emer: $emer}) RETURN k
              `,
        {
          emer: klinika.emer,
        }
      );
      await session.close();
      return result;
    } catch (error) {
      console.error(error);
      await session.close();
      return null;
    }
  }
  return klinikaFromDb;
};
