import { UserStatePayload } from 'mweb/chat/chatClient';
import { Badge } from 'mweb/chat/badgerService';
import {
  createMessageData,
  MessageData,
} from 'mweb/chat/events/utils/createMessageData';
import idCreator from 'mweb/chat/events/utils/idCreator';

export const SUBSCRIPTION = 'SUBSCRIPTION';
export const RESUBSCRIPTION = 'RESUBSCRIPTION';
export type SubscribeEventType = typeof SUBSCRIPTION | typeof RESUBSCRIPTION;

export interface SubscriptionEvent {
  type: typeof SUBSCRIPTION;
  id: string;
  isPrime?: boolean;
  username: string;
  channel: string;
}

export interface ResubscriptionEvent extends Partial<MessageData> {
  type: typeof RESUBSCRIPTION;
  id: string;
  isPrime?: boolean;
  months?: number;
  channel: string;
}

export type SubscribeEvent = SubscriptionEvent | ResubscriptionEvent;

export function subscriptionEvent(
  channel: string,
  username: string,
  isPrime: boolean,
): SubscriptionEvent {
  return {
    type: SUBSCRIPTION,
    id: idCreator(`${username}-sub`),
    channel: channel,
    isPrime,
    username,
  };
}

function usernameOnlyMessageData(username: string): Partial<MessageData> {
  return {
    user: {
      usernameDisplay: username,
      username,
      color: null,
      isIntl: false,
    },
  };
}

export function resubscriptionEvent(
  channel: string,
  username: string,
  isPrime: boolean,
  months: number,
  message: string,
  userstate: UserStatePayload,
  badges: Badge[],
): ResubscriptionEvent {
  const messageData = message
    ? createMessageData(message, userstate, badges)
    : usernameOnlyMessageData(username);
  return {
    ...messageData,
    type: RESUBSCRIPTION,
    id: idCreator(`${username}-sub`),
    channel: channel,
    isPrime,
    months,
  };
}
