// Copyright 2022 Signal Messenger, LLC
// SPDX-License-Identifier: AGPL-3.0-only

import { ContentHint } from '@signalapp/libsignal-client';

import * as Errors from '../../types/errors.std.ts';
import { getSendOptions } from '../../util/getSendOptions.preload.ts';
import {
  isDirectConversation,
  isMe,
} from '../../util/whatTypeOfConversation.dom.ts';
import {
  handleMultipleSendErrors,
  maybeExpandErrors,
} from './handleMultipleSendErrors.std.ts';
import { ourProfileKeyService } from '../../services/ourProfileKey.std.ts';

import type { ConversationModel } from '../../models/conversations.preload.ts';
import type {
  ConversationQueueJobBundle,
  DeleteStoryForEveryoneJobData,
} from '../conversationJobQueue.preload.ts';
import { getUntrustedConversationServiceIds } from './getUntrustedConversationServiceIds.dom.ts';
import { handleMessageSend } from '../../util/handleMessageSend.preload.ts';
import { getMessageById } from '../../messages/getMessageById.preload.ts';
import { isNotNil } from '../../util/isNotNil.std.ts';
import type { CallbackResultType } from '../../textsecure/Types.d.ts';
import type { MessageModel } from '../../models/messages.preload.ts';
import { SendMessageProtoError } from '../../textsecure/Errors.std.ts';
import { strictAssert } from '../../util/assert.std.ts';
import type { LoggerType } from '../../types/Logging.std.ts';
import { normalizeStoryDistributionId } from '../../types/StoryDistributionId.std.ts';
import { isStory } from '../../messages/helpers.std.ts';
import { itemStorage } from '../../textsecure/Storage.preload.ts';
import { shouldSendToDirectConversation } from './shouldSendToConversation.preload.ts';

export async function sendDeleteStoryForEveryone(
  ourConversation: ConversationModel,
  {
    isFinalAttempt,
    messaging,
    shouldContinue,
    timestamp,
    timeRemaining,
    log,
  }: ConversationQueueJobBundle,
  data: DeleteStoryForEveryoneJobData
): Promise<void> {
  const { storyId, targetTimestamp, updatedStoryRecipients } = data;

  const logId = `sendDeleteStoryForEveryone(${storyId})`;

  const message = await getMessageById(storyId);
  if (!message) {
    log.error(`${logId}: Failed to fetch message. Failing job.`);
    return;
  }

  if (!shouldContinue) {
    log.info(`${logId}: Ran out of time. Giving up on sending`);
    void updateMessageWithFailure(
      message,
      [new Error('Ran out of time!')],
      log
    );
    return;
  }

  strictAssert(
    isMe(ourConversation.attributes),
    'Story DOE must be sent on our conversaton'
  );
  strictAssert(isStory(message.attributes), 'Story message must be a story');

  const sendType = 'deleteForEveryone';
  const contentHint = ContentHint.Resendable;

  const deletedForEveryoneSendStatus = message.get(
    'deletedForEveryoneSendStatus'
  );
  strictAssert(
    deletedForEveryoneSendStatus,
    `${logId}: message does not have deletedForEveryoneSendStatus`
  );
  const recipientIds = Object.entries(deletedForEveryoneSendStatus)
    .filter(([_, isSent]) => !isSent)
    .map(([conversationId]) => conversationId);

  const untrustedServiceIds = getUntrustedConversationServiceIds(recipientIds);
  if (untrustedServiceIds.length) {
    window.reduxActions.conversations.conversationStoppedByMissingVerification({
      conversationId: ourConversation.id,
      untrustedServiceIds,
    });
    throw new Error(
      `Delete for everyone blocked because ${untrustedServiceIds.length} ` +
        'conversation(s) were untrusted. Failing this attempt.'
    );
  }

  const recipientConversations = recipientIds
    .map(conversationId => {
      const conversation = window.ConversationController.get(conversationId);
      if (!conversation) {
        log.error(`${logId}: conversation not found for ${conversationId}`);
        return undefined;
      }
      if (!isDirectConversation(conversation.attributes)) {
        log.error(`${logId}: conversation ${conversationId} is not direct`);
        return undefined;
      }

      const [ok, refusal] = shouldSendToDirectConversation(conversation);
      if (!ok) {
        log.info(`${logId}: ${refusal.logLine}`);
        void updateMessageWithFailure(message, [refusal.error], log);
        return undefined;
      }

      return conversation;
    })
    .filter(isNotNil);

  const hadSuccessfulSends = doesMessageHaveSuccessfulSends(message);
  let didSuccessfullySendOne = false;

  // Special case - we have no one to send it to so just send the sync message.
  if (recipientConversations.length === 0) {
    didSuccessfullySendOne = true;
  }

  const profileKey = await ourProfileKeyService.get();

  await Promise.all(
    recipientConversations.map(conversation => {
      return conversation.queueJob(
        'conversationQueue/sendStoryDeleteForEveryone',
        async () => {
          log.info(
            `${logId}: Sending deleteStoryForEveryone with timestamp ${timestamp}`
          );

          const sendOptions = await getSendOptions(conversation.attributes, {
            story: true,
          });

          try {
            const serviceId = conversation.getSendTarget();
            strictAssert(serviceId, 'conversation has no service id');

            const ourAci = itemStorage.user.getCheckedAci();

            await handleMessageSend(
              messaging.sendMessageToServiceId({
                serviceId,
                messageOptions: {
                  deleteForEveryone: {
                    isAdminDelete: false,
                    targetSentTimestamp: targetTimestamp,
                    targetAuthorAci: ourAci,
                  },
                  timestamp,
                  profileKey: conversation.get('profileSharing')
                    ? profileKey
                    : undefined,
                },
                groupId: undefined,
                contentHint,
                options: sendOptions,
                urgent: true,
                story: true,
              }),
              {
                messageIds: [storyId],
                sendType,
              }
            );

            didSuccessfullySendOne = true;

            await updateMessageWithSuccessfulSends(message, {
              dataMessage: undefined,
              editMessage: undefined,
              successfulServiceIds: [serviceId],
            });
          } catch (error: unknown) {
            if (error instanceof SendMessageProtoError) {
              await updateMessageWithSuccessfulSends(message, error);
            }

            const errors = maybeExpandErrors(error);
            await handleMultipleSendErrors({
              errors,
              isFinalAttempt,
              log,
              markFailed: () => updateMessageWithFailure(message, errors, log),
              timeRemaining,
              toThrow: error,
            });
          }
        }
      );
    })
  );

  if (!window.ConversationController.doWeHaveOtherDevices()) {
    log.info(`${logId}: We have no other devices; not sending sync`);
    return;
  }

  // Send sync message exactly once per job. If any of the sends are successful
  // and we didn't send the DOE itself before - it is a good time to send the
  // sync message.
  if (!hadSuccessfulSends && didSuccessfullySendOne) {
    log.info(`${logId}: Sending sync message`);
    const options = await getSendOptions(ourConversation.attributes, {
      syncMessage: true,
    });

    const destinationServiceId = ourConversation.getCheckedServiceId(
      'deleteStoryForEveryone'
    );

    // Sync message for other devices
    await handleMessageSend(
      messaging.sendSyncMessage({
        destinationE164: undefined,
        destinationServiceId,
        storyMessageRecipients: updatedStoryRecipients?.map(
          ({
            destinationServiceId: legacyDestinationUuid,
            distributionListIds,
            ...rest
          }) => {
            return {
              // The field was renamed.
              legacyDestinationUuid,
              distributionListIds: distributionListIds?.map(id => {
                return normalizeStoryDistributionId(
                  id,
                  'sendDeleteStoryForEveryone',
                  log
                );
              }),
              ...rest,
            };
          }
        ),
        expirationStartTimestamp: null,
        isUpdate: true,
        options,
        timestamp: message.get('timestamp'),
        urgent: false,
      }),
      { messageIds: [storyId], sendType }
    );
  }
}

function doesMessageHaveSuccessfulSends(message: MessageModel): boolean {
  const map = message.get('deletedForEveryoneSendStatus') ?? {};

  return Object.values(map).includes(true);
}

async function updateMessageWithSuccessfulSends(
  message: MessageModel,
  result?: CallbackResultType | SendMessageProtoError
): Promise<void> {
  if (!result) {
    message.set({
      deletedForEveryoneSendStatus: {},
      deletedForEveryoneFailed: undefined,
    });
    await window.MessageCache.saveMessage(message.attributes);

    return;
  }

  const deletedForEveryoneSendStatus = {
    ...message.get('deletedForEveryoneSendStatus'),
  };

  result.successfulServiceIds?.forEach(serviceId => {
    const conversation = window.ConversationController.get(serviceId);
    if (!conversation) {
      return;
    }
    deletedForEveryoneSendStatus[conversation.id] = true;
  });

  message.set({
    deletedForEveryoneSendStatus,
    deletedForEveryoneFailed: undefined,
  });
  await window.MessageCache.saveMessage(message.attributes);
}

async function updateMessageWithFailure(
  message: MessageModel,
  errors: ReadonlyArray<unknown>,
  log: LoggerType
): Promise<void> {
  log.error(
    'updateMessageWithFailure: Setting this set of errors',
    errors.map(Errors.toLogFormat)
  );

  message.set({ deletedForEveryoneFailed: true });
  await window.MessageCache.saveMessage(message.attributes);
}
