import {User} from '@interfaces/user';
import {LOCAL_INITIAL_VERSION} from '@modules/chats/constants';
import {InsertUser, SelectUser} from '@modules/chats/db/interfaces';
import {
  ChatUserStatus,
  HuDataMember,
  Message,
  ChatUser,
} from '@modules/chats/interfaces';

export const mapHuMemberToDB = (user: HuDataMember): InsertUser => {
  const firstName = user.first_name ?? '';
  const lastName = user.last_name ?? '';

  return {
    id: user.id,
    email: user.email ?? null,
    first_name: firstName,
    last_name: lastName,
    name: `${firstName} ${lastName}`.trim(),
    picture_asset_url: user.picture_asset_url ?? null,
    employee_internal_id: user.employee_internal_id ?? null,
    status: user.deleted_at
      ? ChatUserStatus.Deleted
      : user.status || ChatUserStatus.Active,
    deleted_at: user.deleted_at,
    version: user.version || 0,
  };
};

export const mapUserFromDB = (user: SelectUser): HuDataMember => {
  return {
    id: user.id || 0,
    picture_asset_url: user.picture_asset_url || null,
    first_name: user.first_name,
    last_name: user.last_name,
    employee_internal_id: user.employee_internal_id || '',
    version: user.version || 0,
    email: user.email || '',
    status: user.status as ChatUserStatus,
    deleted_at: user.deleted_at || undefined,
  };
};

export const mapUserFromMessage = (message: Message): HuDataMember => {
  return {
    email: message.user,
    id: Number(message.user),
    first_name: message.username,
    last_name: '',
    employee_internal_id: '',
    picture_asset_url: message.sender_profile_picture || null,
    status: ChatUserStatus.Active,
    version: 0,
  };
};

export const mapUserFromServer = (user: ChatUser): HuDataMember => {
  return {
    id: Number(user.id),
    email: user.profile.email,
    first_name: user.hu_data.member.first_name,
    last_name: user.hu_data.member.last_name,
    employee_internal_id: user.hu_data.member.employee_internal_id,
    picture_asset_url: user.hu_data.member.picture_asset_url,
    status: user.hu_data.member.deleted_at
      ? ChatUserStatus.Deleted
      : user.hu_data.member.status || ChatUserStatus.Active,
    deleted_at: user.hu_data.member.deleted_at,
    version: user.hu_data.member.version || 0,
  };
};

export const mapGlobalUserToChatUser = (user: User): HuDataMember => {
  return {
    id: user.id,
    email: user.email || null,
    first_name: user.firstName,
    last_name: user.lastName,
    employee_internal_id: user.employeeInternalId,
    picture_asset_url: user.profilePicture,
    status: user.active ? ChatUserStatus.Active : ChatUserStatus.Deleted,
    deleted_at: user.deleted ? Date.now() : undefined,
    version: LOCAL_INITIAL_VERSION,
  };
};
