import Foundation
import SwiftData

@Model
final class Tag {
    @Attribute(.unique) var id: UUID
    var name: String
    var nameEN: String
    var color: String
    var maxPerWeek: Int?
    var noConsecutive: Bool
    var noDuplicateInDay: Bool
    var mealTypeRestriction: String? // "lunch", "dinner", nil
    var isDefault: Bool
    var sortOrder: Int

    init(
        id: UUID = UUID(),
        name: String,
        nameEN: String = "",
        color: String,
        maxPerWeek: Int? = nil,
        noConsecutive: Bool = false,
        noDuplicateInDay: Bool = false,
        mealTypeRestriction: String? = nil,
        isDefault: Bool = true,
        sortOrder: Int = 0
    ) {
        self.id = id
        self.name = name
        self.nameEN = nameEN
        self.color = color
        self.maxPerWeek = maxPerWeek
        self.noConsecutive = noConsecutive
        self.noDuplicateInDay = noDuplicateInDay
        self.mealTypeRestriction = mealTypeRestriction
        self.isDefault = isDefault
        self.sortOrder = sortOrder
    }

    func localizedName(language: AppLanguage) -> String {
        switch language.resolved() {
        case .spanish: return name
        case .english: return nameEN.isEmpty ? name : nameEN
        case .system: return name
        }
    }

    var rulesDescription: String {
        localizedRulesDescription(language: .spanish)
    }

    func localizedRulesDescription(language: AppLanguage) -> String {
        let resolvedLanguage = language.resolved()
        var parts: [String] = []
        if let max = maxPerWeek {
            switch resolvedLanguage {
            case .spanish:
                parts.append("Max \(max)/semana")
            case .english:
                parts.append("Max \(max)/week")
            case .system:
                parts.append("Max \(max)/week")
            }
        }
        if noConsecutive {
            parts.append(resolvedLanguage == .spanish ? "no consecutivo" : "no consecutive")
        }
        if noDuplicateInDay {
            parts.append(resolvedLanguage == .spanish ? "no mismo día" : "no same day")
        }
        if let restriction = mealTypeRestriction {
            if resolvedLanguage == .spanish {
                parts.append(restriction == "lunch" ? "solo comida" : "solo cena")
            } else {
                parts.append(restriction == "lunch" ? "lunch only" : "dinner only")
            }
        }
        return parts.isEmpty ? (resolvedLanguage == .spanish ? "Sin límite" : "No limit") : parts.joined(separator: ", ")
    }
}
