import Foundation
import SwiftData

@Model
final class MealSlot {
    @Attribute(.unique) var id: UUID
    var dayOfWeek: Int // 0=Monday, 6=Sunday
    var mealType: String // "lunch", "dinner"
    var dishId: UUID?
    var calendarEventId: String?
    var isRuleOverridden: Bool

    var weekPlan: WeekPlan?

    init(
        id: UUID = UUID(),
        dayOfWeek: Int,
        mealType: String,
        dishId: UUID? = nil,
        calendarEventId: String? = nil,
        isRuleOverridden: Bool = false
    ) {
        self.id = id
        self.dayOfWeek = dayOfWeek
        self.mealType = mealType
        self.dishId = dishId
        self.calendarEventId = calendarEventId
        self.isRuleOverridden = isRuleOverridden
    }

    var mealTypeEnum: MealType {
        get { MealType(rawValue: mealType) ?? .dinner }
        set { mealType = newValue.rawValue }
    }
}

extension MealSlot {
    static func preferredForDuplicateResolution(_ slots: [MealSlot]) -> MealSlot {
        slots.sorted { lhs, rhs in
            let lhsHasDish = lhs.dishId != nil
            let rhsHasDish = rhs.dishId != nil
            if lhsHasDish != rhsHasDish { return lhsHasDish }

            let lhsHasEvent = lhs.calendarEventId != nil
            let rhsHasEvent = rhs.calendarEventId != nil
            if lhsHasEvent != rhsHasEvent { return lhsHasEvent }

            return lhs.id.uuidString < rhs.id.uuidString
        }.first ?? slots[0]
    }
}
