import {LOCAL_INITIAL_VERSION} from '@modules/chats/constants';
import {
  InsertGroupMembership,
  SelectGroupMembership,
  SelectUser,
} from '@modules/chats/db/interfaces';
import {Membership, MembershipFromServer} from '@modules/chats/interfaces';

import {mapUserFromDB} from './userMapper';

export const mapMembershipToDB = (membership: {
  user: {id: number};
  channel: string;
  version: number;
  is_admin: boolean;
}): InsertGroupMembership => {
  return {
    user_id: membership.user.id,
    conversation_id: membership.channel,
    version: membership.version,
    is_admin: membership.is_admin,
  };
};

export const mapMembershipsToDB = (
  channel: string,
  memberships: {
    user: {id: number};
    version: number;
    is_admin: boolean;
  }[],
): InsertGroupMembership[] => {
  return memberships.map(membership =>
    mapMembershipToDB({channel, ...membership}),
  );
};

export const mapMembershipFromDB = (membership: {
  users: SelectUser;
  group_memberships: SelectGroupMembership;
}): Membership => {
  return {
    is_admin: membership.group_memberships.is_admin || false,
    version: membership.group_memberships.version || LOCAL_INITIAL_VERSION,
    user: mapUserFromDB(membership.users),
  };
};

export const mapMembershipFromServer = (
  membership: MembershipFromServer,
): Membership => {
  return {
    is_admin: membership.is_admin ?? false,
    version: membership.version,
    user: membership.user.hu_data.member,
  };
};
