// 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.js';
import { getSendOptions } from '../../util/getSendOptions.preload.js';
import {
  isDirectConversation,
  isMe,
} from '../../util/whatTypeOfConversation.dom.js';
import {
  handleMultipleSendErrors,
  maybeExpandErrors,
} from './handleMultipleSendErrors.std.js';
import { ourProfileKeyService } from '../../services/ourProfileKey.std.js';

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

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,
            });
          }
        }
      );
    })
  );

  // 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, ...rest }) => {
            return {
              // The field was renamed.
              legacyDestinationUuid,
              ...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).some(value => value === 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);
}
