import Foundation
import CoreData

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

    @NSManaged public var id: UUID
    @NSManaged public var currency: String
    @NSManaged public var defaultNotificationTime: Date?
    @NSManaged public var enableAnalytics: Bool
    @NSManaged public var onboardingCompleted: Bool
    @NSManaged public var lastSyncDate: Date?
    @NSManaged public var createdAt: Date
    @NSManaged public var inputMode: String
    @NSManaged public var selectedAccountId: UUID?
    @NSManaged public var showAllAccounts: Bool

    public override func awakeFromInsert() {
        super.awakeFromInsert()
        id = UUID()
        let localeCode = Locale.current.currency?.identifier
        currency = CurrencyPicker.commonCodes.contains(localeCode ?? "")
            ? (localeCode ?? "EUR")
            : "EUR"
        enableAnalytics = true
        onboardingCompleted = false
        inputMode = InputMode.simple.rawValue
        showAllAccounts = true
        createdAt = Date()

        // Default notification time: 9:00 AM
        var components = DateComponents()
        components.hour = 9
        components.minute = 0
        defaultNotificationTime = Calendar.current.date(from: components)
    }
}

// MARK: - Computed Properties

extension AppSettings {
    var currencySymbol: String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.currencyCode = currency
        return formatter.currencySymbol ?? "€"
    }

    var notificationTimeString: String {
        guard let time = defaultNotificationTime else { return "9:00 AM" }
        let formatter = DateFormatter()
        formatter.timeStyle = .short
        return formatter.string(from: time)
    }
}

// MARK: - Static Helpers

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

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

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

    static func markOnboardingComplete(in context: NSManagedObjectContext) {
        let settings = getOrCreate(in: context)
        settings.onboardingCompleted = true
        try? context.save()
    }
}
