import {
  TemplateDto,
  CampaignTemplateResponse,
  CampaignTemplateCreateDto,
} from "types/templates";
import notification from "utils/notification";
import { Maybe } from "utils/types";
import { Api } from "./api";
import { MessagingAdaptor } from "./api/messaging-adaptor";

export default class CampaignTemplateService {
  constructor(
    private readonly api: Api,
    private messagingAdaptor: MessagingAdaptor,
  ) {
    this.api = api;
  }

  async getCampaignTemplate(templateId: string): Promise<Maybe<TemplateDto>> {
    const res = await this.messagingAdaptor.getCampaignTemplate(templateId);

    if (!res) {
      return void notification.error({
        message: "Something went wrong while querying campaign template",
      });
    }
    if (!("ok" in res)) {
      return void notification.error({ message: res.message });
    }

    return res.response.campaignTemplate;
  }

  async createCampaignTemplate(
    template: CampaignTemplateCreateDto,
  ): Promise<Maybe<TemplateDto>> {
    const res = await this.messagingAdaptor.createCampaignTemplate(template);

    if (!res) {
      return void notification.error({
        message: "Something went wrong while creating campaign template",
      });
    }
    if (!("ok" in res)) {
      return void notification.error({ message: res.message });
    }

    return (res.response as CampaignTemplateResponse).campaignTemplate;
  }

  async updateCampaignTemplate(
    templateId: string,
    template: CampaignTemplateCreateDto,
  ): Promise<Maybe<boolean>> {
    const res = await this.messagingAdaptor.updateCampaignTemplate(
      templateId,
      template,
    );

    if (!res) {
      return void notification.error({
        message: "Something went wrong while updating campaign template",
      });
    }
    if (!("ok" in res)) {
      return void notification.error({ message: res.message });
    }

    notification.success({
      message: "Campaign Template updated successfully",
    });

    return res.ok;
  }
}
