import Foundation
import SwiftData

struct DefaultDataService {

    static func createDefaultTags(context: ModelContext, saveImmediately: Bool = true) {
        let defaults: [(name: String, nameEN: String, color: String, maxPerWeek: Int?, noConsecutive: Bool, noDuplicateInDay: Bool, mealTypeRestriction: String?, sortOrder: Int)] = [
            ("Carne", "Meat", "#E74C3C", 3, true, true, nil, 0),
            ("Pescado", "Fish", "#3498DB", 2, true, true, nil, 1),
            ("Legumbres", "Legumes", "#95A5A6", 2, false, true, nil, 2),
            ("Verduras", "Vegetables", "#2ECC71", nil, false, false, nil, 3),
            ("Huevos", "Eggs", "#F1C40F", 2, false, true, nil, 4),
            ("Pasta/Arroz", "Pasta/Rice", "#D4AC6E", 3, true, false, nil, 5),
            ("Solo Cena", "Dinner Only", "#9B59B6", nil, false, false, "dinner", 6),
            ("Solo Comida", "Lunch Only", "#E67E22", nil, false, false, "lunch", 7),
            ("Con Gluten", "Contains Gluten", "#8B4513", nil, false, false, nil, 8),
            ("Sin Gluten", "Gluten Free", "#1ABC9C", nil, false, false, nil, 9)
        ]

        for d in defaults {
            let tag = Tag(
                name: d.name,
                nameEN: d.nameEN,
                color: d.color,
                maxPerWeek: d.maxPerWeek,
                noConsecutive: d.noConsecutive,
                noDuplicateInDay: d.noDuplicateInDay,
                mealTypeRestriction: d.mealTypeRestriction,
                isDefault: true,
                sortOrder: d.sortOrder
            )
            context.insert(tag)
        }

        if saveImmediately {
            try? context.save()
        }
    }

    static func createDefaultSettings(context: ModelContext) {
        let settings = AppSettings()
        context.insert(settings)
        try? context.save()
    }

    static func createWeekPlan(for weekStart: Date, settings: AppSettings, context: ModelContext) -> WeekPlan {
        let plan = WeekPlan(weekStartDate: weekStart)
        context.insert(plan)

        let maxDay = settings.includeWeekends ? 6 : 4
        let mealTypes: [String] = {
            switch settings.mealWindowsEnum {
            case .dinnerOnly: return ["dinner"]
            case .lunchOnly: return ["lunch"]
            case .both: return ["lunch", "dinner"]
            }
        }()

        for day in 0...maxDay {
            for mealType in mealTypes {
                let slot = MealSlot(dayOfWeek: day, mealType: mealType)
                slot.weekPlan = plan
                plan.slots.append(slot)
                context.insert(slot)
            }
        }

        try? context.save()
        return plan
    }
}
