import Forum from '../models/forum/forum.js';
import ForumPermission from '../models/forum/forum_permission.js';
import ForumForumPermission from '../models/forum/forum_forum_permission.js';

const initializeForum = async () => {
    const permissions = [
        { name: 'all', value: null },
        { name: 'user', value: null },
        { name: 'admin', value: null },
        { name: 'age', value: '14' },
        { name: 'teammember', value: null }
    ];
    const forums = [
        { name: 'Intern', permissions: ['admin', 'teammember'] },
        { name: 'Flirt', permissions: ['age'] },
        { name: 'Falukant', permissions: ['all'] },
        { name: 'Politik', permissions: ['all'] },
        { name: 'Schule', permissions: ['all'] }
    ];
    const permissionMap = {};
    for (const perm of permissions) {
        const [permission] = await ForumPermission.findOrCreate({
            where: { name: perm.name },
            defaults: { name: perm.name, value: perm.value }
        });
        permissionMap[perm.name] = permission.id;
    }
    for (const forum of forums) {
        try {
            const [createdForum] = await Forum.findOrCreate({
                where: { name: forum.name },
                defaults: { name: forum.name }
            });
            for (const permissionName of forum.permissions) {
                const permissionId = permissionMap[permissionName];
                await ForumForumPermission.findOrCreate({
                    where: { forumId: createdForum.id, permissionId: permissionId },
                    defaults: { forumId: createdForum.id, permissionId: permissionId },
                });
            }
            console.log(`Forum '${forum.name}' erfolgreich erstellt oder aktualisiert.`);
        } catch (error) {
            console.error(`Fehler beim Erstellen des Forums '${forum.name}': ${error.message}`);
        }
    }
};

export default initializeForum;
