import Foundation
import CoreData
import SwiftUI

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

    @NSManaged public var id: UUID
    @NSManaged public var name: String
    @NSManaged public var colorHex: String
    @NSManaged public var icon: String
    @NSManaged public var sortOrder: Int16
    @NSManaged public var createdAt: Date
    @NSManaged public var allocationTarget: NSNumber?
    @NSManaged public var sources: NSSet?

    public override func awakeFromInsert() {
        super.awakeFromInsert()
        id = UUID()
        createdAt = Date()
        sortOrder = 0
        colorHex = "#3B82F6"
        icon = "chart.pie.fill"
        name = ""
    }
}

// MARK: - Computed Properties

extension Category {
    var color: Color {
        Color(hex: colorHex) ?? .blue
    }

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

    var sourceCount: Int {
        guard !isDeleted, !isFault else { return 0 }
        return sources?.count ?? 0
    }

    var totalValue: Decimal {
        sourcesArray.reduce(Decimal.zero) { $0 + $1.latestValue }
    }
}

// MARK: - Generated accessors for sources

extension Category {
    @objc(addSourcesObject:)
    @NSManaged public func addToSources(_ value: InvestmentSource)

    @objc(removeSourcesObject:)
    @NSManaged public func removeFromSources(_ value: InvestmentSource)

    @objc(addSources:)
    @NSManaged public func addToSources(_ values: NSSet)

    @objc(removeSources:)
    @NSManaged public func removeFromSources(_ values: NSSet)
}

// MARK: - Default Categories

extension Category {
    static let defaultCategories: [(name: String, colorHex: String, icon: String)] = [
        ("Stocks", "#10B981", "chart.line.uptrend.xyaxis"),
        ("Cash", "#6B7280", "banknote.fill"),
        ("Crypto", "#8B5CF6", "bitcoinsign.circle.fill"),
        ("Real Estate", "#F59E0B", "house.fill"),
        ("Bonds", "#3B82F6", "building.columns.fill"),
        ("Retirement", "#14B8A6", "person.fill"),
        ("Other", "#64748B", "ellipsis.circle.fill"),
        ("ETFs", "#EC4899", "chart.bar.fill")
    ]

    static func createDefaultCategories(in context: NSManagedObjectContext) {
        for (index, categoryData) in defaultCategories.enumerated() {
            let category = Category(context: context)
            category.name = categoryData.name
            category.colorHex = categoryData.colorHex
            category.icon = categoryData.icon
            category.sortOrder = Int16(index)
        }

        try? context.save()
    }
}
