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

import Foundation
import SignalServiceKit
import SignalUI

struct ArchivedPaymentHistoryItem: PaymentsHistoryItem {

    private let archivedPayment: ArchivedPayment
    let displayName: String

    private let paymentInfo: TSArchivedPaymentInfo
    let isIncoming: Bool

    let address: SignalServiceKit.SignalServiceAddress?

    init?(
        archivedPayment: ArchivedPayment,
        address: SignalServiceAddress?,
        displayName: String,
        interaction: TSInteraction,
    ) {
        self.archivedPayment = archivedPayment
        self.displayName = displayName
        self.address = address

        switch interaction {
        case let interaction as OWSIncomingArchivedPaymentMessage:
            self.isIncoming = true
            self.paymentInfo = interaction.archivedPaymentInfo
        case let interaction as OWSOutgoingArchivedPaymentMessage:
            self.isIncoming = false
            self.paymentInfo = interaction.archivedPaymentInfo
        default:
            return nil
        }
    }

    var isOutgoing: Bool {
        !isIncoming
    }

    var isUnidentified: Bool {
        archivedPayment.interactionUniqueId == nil
    }

    var isFailed: Bool {
        return archivedPayment.status.isFailure
    }

    var isDefragmentation: Bool {
        return false
    }

    var receiptData: Data? {
        archivedPayment.receipt
    }

    var paymentAmount: TSPaymentAmount? {
        return SUIEnvironment.shared.paymentsImplRef.unmaskReceiptAmount(
            data: archivedPayment.receipt,
        )?.tsPaymentAmount
    }

    var formattedFeeAmount: String? {
        guard
            let archivedFee = paymentInfo.fee,
            let fee = PaymentsFormat.formatFromArchive(amount: archivedFee)
        else { return nil }
        return PaymentsFormat.format(
            amountString: fee,
            withCurrencyCode: true,
            withSpace: true,
        )
    }

    var paymentType: TSPaymentType {
        isIncoming ? .incomingPayment : .outgoingPayment
    }

    var paymentState: TSPaymentState {
        return .incomingComplete
    }

    var ledgerBlockDate: Date? {
        guard
            let timestamp = archivedPayment.blockTimestamp,
            timestamp > 0
        else { return nil }
        return Date(millisecondsSince1970: timestamp)
    }

    var ledgerBlockIndex: UInt64? {
        archivedPayment.blockIndex
    }

    var isUnread: Bool {
        return false
    }

    var memoMessage: String? {
        paymentInfo.note
    }

    var attributedPaymentAmount: NSAttributedString? {
        guard
            let archivedAmount = paymentInfo.amount,
            let amount = PaymentsFormat.formatFromArchive(amount: archivedAmount)
        else { return nil }
        let formattedAmount = PaymentsFormat.format(
            amountString: amount,
            withCurrencyCode: false,
            withSpace: false,
            isIncoming: isIncoming,
        )
        return PaymentsFormat.attributedFormat(mobileCoinString: formattedAmount, withSpace: false)
    }

    var formattedPaymentAmount: String? {
        guard
            let archivedAmount = paymentInfo.amount,
            let amount = PaymentsFormat.formatFromArchive(amount: archivedAmount)
        else { return nil }
        return PaymentsFormat.format(
            amountString: amount,
            withCurrencyCode: true,
            withSpace: true,
        )
    }

    func statusDescription(isLongForm: Bool) -> String? {
        return archivedPayment.statusDescription(isOutgoing: isOutgoing)
    }

    /// Read status is only tracked on TSPaymentModels, so there's not really anything to do here.
    func markAsRead(tx: SignalServiceKit.DBWriteTransaction) { }

    /// Reload is used on payment details to track updates to the TSPaymentModel.
    /// Since ArchivedPayments aren't updated, reloading here isn't necessary.
    func reload(tx: SignalServiceKit.DBReadTransaction) -> Self? {
        return self
    }
}
