import { getSDKConfig } from 'config'

import {
  LinkRedirect,
  LinkRedirectDto,
  LinkRedirectUpdateStatusDto
} from 'types/linkRedirects'

import ProfileService, { Maybe } from '@komi-app/profiles-sdk'

export default class LinkRedirectServiceV1 {
  private profileId = ''
  private profileService: ProfileService

  constructor() {
    this.profileService = new ProfileService(getSDKConfig('profiles'))
  }

  init(profileId: string) {
    this.profileId = profileId
    this.profileService.init(profileId)
  }

  getLinkRedirect = async (): Promise<
    Maybe<{ linkRedirect: LinkRedirect }>
  > => {
    const linkRedirect = await this.profileService.getLinkRedirect()

    if (!linkRedirect) return void 0

    const {
      profileId: talentProfileId,
      isEnabled,
      link,
      scheduledEndTimestamp: endTimestamp,
      scheduledStartTimestamp: startTimestamp,
      scheduledTimezone: timezone
    } = linkRedirect

    return {
      linkRedirect: {
        talentProfileId,
        isEnabled,
        link,
        endTimestamp: new Date(endTimestamp).getTime(),
        startTimestamp: new Date(startTimestamp).getTime(),
        timezone
      }
    }
  }

  saveLinkRedirect = async (
    linkRedirect: LinkRedirectDto
  ): Promise<Maybe<LinkRedirect>> => {
    if (!linkRedirect.endTimestamp) throw new TypeError('Missing end time')

    if (!linkRedirect.startTimestamp) throw new TypeError('Missing start time')

    if (!linkRedirect.timezone) throw new TypeError('Missing timezone')

    const lr = await this.profileService.setLinkRedirect({
      isEnabled: linkRedirect.isEnabled,
      link: linkRedirect.link,
      scheduledTimezone: linkRedirect.timezone!,
      scheduledEndTimestamp: new Date(linkRedirect.endTimestamp!).toISOString(),
      scheduledStartTimestamp: new Date(
        linkRedirect.startTimestamp!
      ).toISOString()
    })

    if (!lr) return void 0

    const talentProfileId = this.profileId

    const {
      isEnabled,
      link,
      scheduledEndTimestamp: endTimestamp,
      scheduledStartTimestamp: startTimestamp,
      scheduledTimezone: timezone
    } = lr

    return {
      talentProfileId,
      isEnabled: isEnabled,
      link,
      endTimestamp: new Date(endTimestamp).getTime(),
      startTimestamp: new Date(startTimestamp).getTime(),
      timezone
    }
  }

  updateLinkRedirectStatus = async ({
    isEnabled
  }: LinkRedirectUpdateStatusDto): Promise<Maybe<LinkRedirect>> => {
    await this.profileService.enableLinkRedirect(isEnabled)
    return
  }

  deleteLinkRedirect = async (): Promise<Maybe<LinkRedirectDto>> => {
    await this.profileService.deleteLinkRedirect()
    return
  }
}
