import UserParamType from '../models/type/user_param.js';
import SettingsType from '../models/type/settings.js';
import UserParamValue from '../models/type/user_param_value.js';
import Interest from '../models/type/interest.js';
import { Op,  } from 'sequelize';
import InterestTranslation from '../models/type/interest_translation.js';
import UserParamVisibilityType from '../models/type/user_param_visibility.js';

const initializeTypes = async () => {
    const settingsTypes = await SettingsType.findAll();
    const settingsTypeMap = settingsTypes.reduce((map, type) => {
        map[type.name] = type.id;
        return map;
    }, {});

    const getSettingsTypeId = (name) => settingsTypeMap[name];
    const getUserParamTypeId = async (name) => {
        const userParamType = await UserParamType.findOne({
            where: {
                description: name
            }
        });
        return userParamType.id;
    };
    const userParams = {
        language: { type: 'singleselect', setting: 'personal' },
        birthdate: { type: 'date', setting: 'personal', immutable: true },
        zip: { type: 'string', setting: 'personal' },
        town: { type: 'string', setting: 'personal' },
        bodyheight: { type: 'float', setting: 'view', unit: 'cm' },
        weight: { type: 'float', setting: 'view', unit: 'kg' },
        eyecolor: { type: 'singleselect', setting: 'view' },
        haircolor: { type: 'singleselect', setting: 'view' },
        hairlength: { type: 'singleselect', setting: 'view' },
        skincolor: { type: 'singleselect', setting: 'view' },
        freckles: { type: 'singleselect', setting: 'view' },
        piercings: { type: 'bool', setting: 'view' },
        tattoos: { type: 'bool', setting: 'view' },
        sexualpreference: { type: 'singleselect', 'setting': 'sexuality', minAge: 14 },
        gender: { type: 'singleselect', setting: 'personal' },
        pubichair: { type: 'singleselect', setting: 'sexuality', minAge: 14 },
        penislength: { type: 'int', setting: 'sexuality', minAge: 14, gender: 'male', unit: 'cm' },
        brasize: { type: 'string', setting: 'sexuality', minAge: 14, gender: 'female' },
        interestedInGender: { type: 'multiselect', setting: 'flirt', minAge: 14},
        hasChildren: { type: 'bool', setting: 'flirt', minAge: 14 },
        willChildren: { type: 'bool', setting: 'flirt', minAge: 14 },
        smokes: { type: 'singleselect', setting: 'flirt', minAge: 14},
        drinks: { type: 'singleselect', setting: 'flirt', minAge: 14 },
    };
    let orderId = 1;
    for (const key of Object.keys(userParams)) {
        const item = userParams[key];
        const createItem = { description: key, datatype: item.type, settingsId: getSettingsTypeId(item.setting), orderId: orderId++ };
        if (item.minAge) createItem.minAge = item.minAge;
        if (item.gender) createItem.gender = item.gender;
        if (item.unit) createItem.unit = item.unit;
        if (item.immutable) createItem.immutable = item.immutable;
        await UserParamType.findOrCreate({ 
            where: { description: key },
            defaults: createItem
        });
    }
    const valuesList = {
        gender: ['male', 'female', 'transfemale', 'transmale', 'nonbinary'],
        language: ['de', 'en'],
        eyecolor: ['blue', 'green', 'brown', 'black', 'grey', 'hazel', 'amber', 'red', 'other'],
        haircolor: ['black', 'brown', 'blonde', 'red', 'grey', 'white', 'other'],
        hairlength: ['short', 'medium', 'long', 'bald', 'other'],
        skincolor: ['light', 'medium', 'dark', 'other'],
        freckles: ['much', 'medium', 'less', 'none'],
        sexualpreference: ['straight', 'gay', 'bi', 'pan', 'asexual'],
        pubichair: ['none', 'short', 'medium', 'long', 'hairy', 'waxed', 'landingstrip', 'bikinizone', 'other'],
        interestedInGender: ['male', 'female'],
        smokes: ['never', 'socially', 'often', 'daily'],
        drinks: ['never', 'socially', 'often', 'daily'],
        brasize: ['Keine', 'AA', 'A', 'B', 'C', 'D', 'E (DD)', 'F (E)', 'G (F)', 'H (FF)', 'I (G)', 'J (GG)', 'K (H)']
    };
    Object.keys(valuesList).forEach(async (key) => {
        const values = valuesList[key];
        const userParamTypeId = await getUserParamTypeId(key);
        let orderId = 1;
        values.forEach(async (value) => {
            await UserParamValue.findOrCreate({
                where: {
                    userParamTypeId: userParamTypeId,
                    value: value
                },
                defaults: { userParamTypeId: userParamTypeId, value: value, orderId: orderId++ }
            })
        });
    });
    const interestsList = {
        music: { adult: false, translation: { value: 'Musik', language: 'de' } },
        piano: { adult: false, translation: { value: 'Klavier', language: 'de' } },
        art: { adult: false, translation: { value: 'Kunst', language: 'de' } },
        photography: { adult: false, translation: { value: 'Fotografie', language: 'de' } },
        gaming: { adult: false, translation: { value: 'Spielen', language: 'de' } },
        sports: { adult: false, translation: { value: 'Sport', language: 'de' } },
        tabletennis: { adult: false, translation: { value: 'Tischtennis', language: 'de' } },
        soccer: { adult: false, translation: { value: 'Fußball', language: 'de' } },
        tennis: { adult: false, translation: { value: 'Tennis', language: 'de' } },
        swimming: { adult: false, translation: { value: 'Schwimmen', language: 'de' } },
        hiking: { adult: false, translation: { value: 'Wandern', language: 'de' } },
        cooking: { adult: false, translation: { value: 'Kochen', language: 'de' } },
        travel: { adult: false, translation: { value: 'Reisen', language: 'de' } },
        movies: { adult: false, translation: { value: 'Filme', language: 'de' } },
        books: { adult: false, translation: { value: 'Bücher', language: 'de' } },
        reading: { adult: false, translation: { value: 'Lesen', language: 'de' } },
        pets: { adult: false, translation: { value: 'Haustiere', language: 'de' } },
        dogs: { adult: false, translation: { value: 'Hunde', language: 'de' } },
        cats: { adult: false, translation: { value: 'Katzen', language: 'de' } },
        plants: { adult: false, translation: { value: 'Pflanzen', language: 'de' } },
        gardening: { adult: false, translation: { value: 'Gartenarbeit', language: 'de' } },
        yoga: { adult: false, translation: { value: 'Yoga', language: 'de' } },
        meditation: { adult: false, translation: { value: 'Meditation', language: 'de' } },
        spirituality: { adult: false, translation: { value: 'Spiritualität', language: 'de' } },
        religion: { adult: false, translation: { value: 'Religion', language: 'de' } },
        politics: { adult: false, translation: { value: 'Politik', language: 'de' } },
        history: { adult: false, translation: { value: 'Geschichte', language: 'de' } },
        science: { adult: false, translation: { value: 'Wissenschaft', language: 'de' } },
        technology: { adult: false, translation: { value: 'Technologie', language: 'de' } },
        fashion: { adult: false, translation: { value: 'Mode', language: 'de' } },
        beauty: { adult: false, translation: { value: 'Schönheit', language: 'de' } },
        fitness: { adult: false, translation: { value: 'Fitness', language: 'de' } },
        health: { adult: false, translation: { value: 'Gesundheit', language: 'de' } },
        nutrition: { adult: false, translation: { value: 'Ernährung', language: 'de' } },
        wellness: { adult: false, translation: { value: 'Wellness', language: 'de' } },
        finance: { adult: false, translation: { value: 'Finanzen', language: 'de' } },
        business: { adult: false, translation: { value: 'Geschäft', language: 'de' } },
        entrepreneurship: { adult: false, translation: { value: 'Unternehmertum', language: 'de' } },
        education: { adult: false, translation: { value: 'Bildung', language: 'de' } },
        learning: { adult: false, translation: { value: 'Lernen', language: 'de' } },
        language: { adult: false, translation: { value: 'Sprache', language: 'de' } },
        culture: { adult: false, translation: { value: 'Kultur', language: 'de' } },
        family: { adult: false, translation: { value: 'Familie', language: 'de' } },
        friends: { adult: false, translation: { value: 'Freunde', language: 'de' } },
        social: { adult: false, translation: { value: 'Soziales', language: 'de' } },
        nightlife: { adult: false, translation: { value: 'Nachtleben', language: 'de' } },
        partying: { adult: false, translation: { value: 'Feiern', language: 'de' } },
        comedy: { adult: false, translation: { value: 'Komödie', language: 'de' } },
        humor: { adult: false, translation: { value: 'Humor', language: 'de' } },
        sex: { adult: true, translation: { value: 'Sex', language: 'de' } },
        romance: { adult: false, translation: { value: 'Romantik', language: 'de' } },
        dating: { adult: true, translation: { value: 'Dating', language: 'de' } },
        relationships: { adult: false, translation: { value: 'Beziehungen', language: 'de' } },
        adventure: { adult: true, translation: { value: 'Abenteuer', language: 'de' } },
        escapade: { adult: true, translation: { value: 'Eskapade', language: 'de' } },
        sexuality: { adult: true, translation: { value: 'Sexualität', language: 'de' } }
    };
    // Stelle sicher, dass die Sprachwerte existieren
    const languages = await UserParamValue.findAll({where: { value: {[Op.in]: ['de', 'en']} } });
    
    // Erstelle fehlende Sprachwerte
    const languageValues = ['de', 'en'];
    for (const langValue of languageValues) {
        if (!languages.find(lang => lang.value === langValue)) {
            console.log(`🌐 Erstelle fehlenden Sprachwert: ${langValue}`);
            await UserParamValue.create({
                value: langValue,
                paramTypeId: 1 // Annahme: Standard-Parametertyp für Sprachen
            });
        }
    }
    
    // Lade die aktualisierten Sprachwerte
    const updatedLanguages = await UserParamValue.findAll({where: { value: {[Op.in]: ['de', 'en']} } });
    
    const languageId = (language) => {
        const lang = updatedLanguages.find((lang) => lang.value === language);
        if (!lang) {
            throw new Error(`Sprachwert '${language}' nicht gefunden in UserParamValue`);
        }
        return lang.id;
    };

    for (const key of Object.keys(interestsList)) {
        try { 
            const value = interestsList[key];
            const [item, created] = await Interest.findOrCreate({
                where: { name: key },
                defaults: { name: key, allowed: true, adultOnly: value.adult },
            });

            if (created) {
                const langId = languageId('de');
                console.log(`✅ Erstelle Interesse: ${key} (ID: ${item.id}, Sprache: ${langId}, Übersetzung: ${value.translation.value})`);
                await InterestTranslation.create({
                    interestsId: item.id,
                    language: langId,
                    translation: value.translation.value
                });
            }
        } catch (error) {
            console.error(`❌ Fehler beim Erstellen des Interesses '${key}':`, error.message);
            throw error;
        }
    }

    const visibilityTypes = ['Invisible', 'OnlyFriends', 'FriendsAndAdults', 'AdultsOnly', 'All'];
    for (const type of visibilityTypes) {
        try {
            await UserParamVisibilityType.findOrCreate({
                where: { description: type },
                defaults: { description: type }
            });
        } catch (error) {
            throw error;
        }
    }
};

export default initializeTypes;
