import Foundation
import CoreData

@objc(PremiumStatus)
public class PremiumStatus: NSManagedObject, Identifiable {
    @nonobjc public class func fetchRequest() -> NSFetchRequest<PremiumStatus> {
        return NSFetchRequest<PremiumStatus>(entityName: "PremiumStatus")
    }

    @NSManaged public var id: UUID
    @NSManaged public var isPremium: Bool
    @NSManaged public var purchaseDate: Date?
    @NSManaged public var productIdentifier: String?
    @NSManaged public var transactionId: String?
    @NSManaged public var isFamilyShared: Bool
    @NSManaged public var lastVerificationDate: Date?
    @NSManaged public var originalPurchaseDate: Date?

    public override func awakeFromInsert() {
        super.awakeFromInsert()
        id = UUID()
        isPremium = false
        isFamilyShared = false
    }
}

// MARK: - Computed Properties

extension PremiumStatus {
    var daysSincePurchase: Int? {
        guard let purchaseDate = purchaseDate else { return nil }
        return Calendar.current.dateComponents([.day], from: purchaseDate, to: Date()).day
    }

    var needsVerification: Bool {
        guard let lastVerification = lastVerificationDate else { return true }
        let hoursSinceVerification = Calendar.current.dateComponents(
            [.hour],
            from: lastVerification,
            to: Date()
        ).hour ?? 0
        return hoursSinceVerification >= 24
    }
}

// MARK: - Static Helpers

extension PremiumStatus {
    static func getOrCreate(in context: NSManagedObjectContext) -> PremiumStatus {
        let request: NSFetchRequest<PremiumStatus> = PremiumStatus.fetchRequest()
        request.fetchLimit = 1

        if let existing = try? context.fetch(request).first {
            return existing
        }

        let new = PremiumStatus(context: context)
        try? context.save()
        return new
    }

    static func updateStatus(
        isPremium: Bool,
        productIdentifier: String?,
        transactionId: String?,
        isFamilyShared: Bool,
        in context: NSManagedObjectContext
    ) {
        let status = getOrCreate(in: context)
        status.isPremium = isPremium
        status.productIdentifier = productIdentifier
        status.transactionId = transactionId
        status.isFamilyShared = isFamilyShared
        status.lastVerificationDate = Date()

        if isPremium && status.purchaseDate == nil {
            status.purchaseDate = Date()
        }

        try? context.save()
    }
}
