import { dataSource } from "../../../data-source";
import { newsletterConfig } from "../../../entity/configuration/newsletterConfig";
import DatabaseActionException from "../../../exceptions/databaseActionException";
import InternalException from "../../../exceptions/internalException";
import { DeleteNewsletterConfigCommand, SetNewsletterConfigCommand } from "./newsletterConfigCommand";

export default abstract class NewsletterConfigCommandHandler {
  /**
   * @description set newsletterConfig
   * @param {SetNewsletterConfigCommand} setNewsletterConfig
   * @returns {Promise<void>}
   */
  static async set(setNewsletterConfig: SetNewsletterConfigCommand): Promise<void> {
    return await dataSource
      .createQueryBuilder()
      .insert()
      .into(newsletterConfig)
      .values({
        comTypeId: setNewsletterConfig.comTypeId,
        config: setNewsletterConfig.config,
      })
      .orUpdate(["config"], ["comTypeId"])
      .execute()
      .then((result) => {})
      .catch((err) => {
        throw new DatabaseActionException("SET", "newsletterConfig", err);
      });
  }

  /**
   * @description delete newsletterConfig
   * @param {DeleteNewsletterConfigCommand} deleteNewsletterConfig
   * @returns {Promise<void>}
   */
  static async delete(deleteNewsletterConfig: DeleteNewsletterConfigCommand): Promise<void> {
    return await dataSource
      .createQueryBuilder()
      .delete()
      .from(newsletterConfig)
      .where("comTypeId = :comTypeId", { comTypeId: deleteNewsletterConfig.comTypeId })
      .execute()
      .then(() => {})
      .catch((err) => {
        throw new InternalException("Failed setting newsletterConfig", err);
      });
  }
}