import {DBTransaction} from '@db/interfaces';
import {
  deleteUserMembership,
  saveMemberships as saveMembershipService,
} from '@modules/chats/db';
import {InsertGroupMembership} from '@modules/chats/db/interfaces';
import {visibleChatStore} from '@modules/chats/store';
import {sentryLogs} from '@shared/utils';

export class MembershipUpdaterServiceClass {
  async saveGroupMemberships({
    channelId,
    memberships,
    tx,
  }: {
    channelId: string;
    memberships: InsertGroupMembership[];
    tx?: DBTransaction;
  }) {
    try {
      await saveMembershipService(memberships, tx);

      // Check if any of the channels is visible in the store
      this.updateGroupInfo(channelId);
    } catch (error) {
      sentryLogs.error({
        message: 'Error saving group memberships',
        module: 'CHATS',
        data: {
          error: error instanceof Error ? error.message : String(error),
        },
      });
    }
  }
  async deleteUserGroupMembership(userId: number, channelId: string) {
    try {
      await deleteUserMembership(userId, channelId);
      this.updateGroupInfo(channelId);
    } catch (error) {
      sentryLogs.error({
        message: 'Error deleting user group membership',
        module: 'CHATS',
        data: {
          error: error instanceof Error ? error.message : String(error),
        },
      });
    }
  }

  // Check if channel is a group and is visible in the store
  updateGroupInfo = (channelId?: string) => {
    const {id, isChannel, getGroupInfo} = visibleChatStore.getState();
    if (isChannel && id === channelId) {
      // Update group summary info in the store
      getGroupInfo(channelId);
    }
  };
}

export const MembershipUpdaterService = new MembershipUpdaterServiceClass();
