import { dataSource } from "../../data-source";
import { webapi } from "../../entity/user/webapi";
import InternalException from "../../exceptions/internalException";

export default abstract class WebapiService {
  /**
   * @description get apis
   * @returns {Promise<Array<webapi>>}
   */
  static async getAll(): Promise<Array<webapi>> {
    return await dataSource
      .getRepository(webapi)
      .createQueryBuilder("webapi")
      .leftJoinAndSelect("webapi.permissions", "permissions")
      .getMany()
      .then((res) => {
        return res;
      })
      .catch((err) => {
        throw new InternalException("webapis not found", err);
      });
  }

  /**
   * @description get api by id
   * @param id number
   * @returns {Promise<webapi>}
   */
  static async getById(id: number): Promise<webapi> {
    return await dataSource
      .getRepository(webapi)
      .createQueryBuilder("webapi")
      .leftJoinAndSelect("webapi.permissions", "permissions")
      .where("webapi.id = :id", { id: id })
      .getOneOrFail()
      .then((res) => {
        return res;
      })
      .catch((err) => {
        throw new InternalException("webapi not found by id", err);
      });
  }

  /**
   * @description get api by token
   * @param token string
   * @returns {Promise<webapi>}
   */
  static async getByToken(token: string): Promise<webapi> {
    return await dataSource
      .getRepository(webapi)
      .createQueryBuilder("webapi")
      .leftJoinAndSelect("webapi.permissions", "permissions")
      .where("webapi.token = :token", { token: token })
      .getOneOrFail()
      .then((res) => {
        return res;
      })
      .catch((err) => {
        throw new InternalException("webapi not found by token", err);
      });
  }

  /**
   * @description get api by id
   * @param id number
   * @returns {Promise<webapi>}
   */
  static async getTokenById(id: number): Promise<webapi> {
    return await dataSource
      .getRepository(webapi)
      .createQueryBuilder("webapi")
      .select("webapi.token")
      .where("webapi.id = :id", { id: id })
      .getOneOrFail()
      .then((res) => {
        return res;
      })
      .catch((err) => {
        throw new InternalException("webapi token not found by id", err);
      });
  }
}