import Foundation
import CoreData

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

    @NSManaged public var id: UUID
    @NSManaged public var name: String
    @NSManaged public var createdAt: Date
    @NSManaged public var currency: String?
    @NSManaged public var inputMode: String
    @NSManaged public var notificationFrequency: String
    @NSManaged public var customFrequencyMonths: Int16
    @NSManaged public var sortOrder: Int16
    @NSManaged public var sources: NSSet?
    @NSManaged public var goals: NSSet?

    public override func awakeFromInsert() {
        super.awakeFromInsert()
        id = UUID()
        createdAt = Date()
        name = "Account"
        inputMode = InputMode.simple.rawValue
        notificationFrequency = NotificationFrequency.monthly.rawValue
        customFrequencyMonths = 1
        sortOrder = 0
    }
}

// MARK: - Constants

extension Account {
    static let defaultAccountName = "Default"
}

// MARK: - Computed Properties

extension Account {
    var sourcesArray: [InvestmentSource] {
        let set = sources as? Set<InvestmentSource> ?? []
        return set.sorted { $0.name < $1.name }
    }

    var goalsArray: [Goal] {
        let set = goals as? Set<Goal> ?? []
        return set.sorted { $0.createdAt < $1.createdAt }
    }

    var frequency: NotificationFrequency {
        NotificationFrequency(rawValue: notificationFrequency) ?? .monthly
    }

    var currencyCode: String? {
        currency?.isEmpty == false ? currency : nil
    }

    var isDefaultAccount: Bool {
        name == Account.defaultAccountName
    }
}

