import fs from 'fs';
import diaryDateActivityService from '../services/diaryDateActivityService.js';
import { emitActivityChanged } from '../services/socketService.js';
import DiaryDate from '../models/DiaryDates.js';

import { devLog, errorLog } from '../utils/logger.js';
export const createDiaryDateActivity = async (req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId } = req.params;
        const { diaryDateId, activity, predefinedActivityId, duration, durationText, orderId, isTimeblock, groupId } = req.body;
        const activityItem = await diaryDateActivityService.createActivity(userToken, clubId, {
            diaryDateId,
            activity,
            predefinedActivityId,
            duration,
            durationText,
            orderId,
            isTimeblock,
            groupId,
        });
        
        // Emit Socket-Event
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (diaryDate?.clubId) {
            emitActivityChanged(diaryDate.clubId, diaryDateId);
        }
        
        res.status(201).json(activityItem);
    } catch (error) {
        devLog(error);
        res.status(500).json({ error: 'Error creating activity' });
    }
};

export const updateDiaryDateActivity = async (req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId, id } = req.params;
        const { predefinedActivityId, customActivityName, duration, durationText, orderId, groupId } = req.body; // Add groupId
        const updatedActivity = await diaryDateActivityService.updateActivity(userToken, clubId, id, {
            predefinedActivityId,
            customActivityName,
            duration,
            durationText,
            orderId,
            groupId, // Pass groupId to the service
        });
        
        // Emit Socket-Event
        if (updatedActivity?.diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(updatedActivity.diaryDateId);
            if (diaryDate?.clubId) {
                emitActivityChanged(diaryDate.clubId, updatedActivity.diaryDateId);
            }
        }
        
        res.status(200).json(updatedActivity);
    } catch (error) {
        res.status(500).json({ error: 'Error updating activity' });
    }
};

export const deleteDiaryDateActivity = async (req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId, id } = req.params;
        
        // Hole diaryDateId vor dem Löschen
        const DiaryDateActivity = (await import('../models/DiaryDateActivity.js')).default;
        const activity = await DiaryDateActivity.findByPk(id);
        const diaryDateId = activity?.diaryDateId;
        
        await diaryDateActivityService.deleteActivity(userToken, clubId, id);
        
        // Emit Socket-Event
        if (diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(diaryDateId);
            if (diaryDate?.clubId) {
                emitActivityChanged(diaryDate.clubId, diaryDateId);
            }
        }
        
        res.status(200).json({ message: 'Activity deleted' });
    } catch (error) {
        res.status(500).json({ error: 'Error deleting activity' });
    }
};

export const updateDiaryDateActivityOrder = async (req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId, id } = req.params;
        const { orderId } = req.body;
        const updatedActivity = await diaryDateActivityService.updateActivityOrder(userToken, clubId, id, orderId);
        
        // Emit Socket-Event
        if (updatedActivity?.diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(updatedActivity.diaryDateId);
            if (diaryDate?.clubId) {
                emitActivityChanged(diaryDate.clubId, updatedActivity.diaryDateId);
            }
        }
        
        res.status(200).json(updatedActivity);
    } catch (error) {
        devLog(error);
        res.status(500).json({ error: 'Error updating activity order' });
    }
};

export const getDiaryDateActivities = async (req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId, diaryDateId } = req.params;
        const activities = await diaryDateActivityService.getActivities(userToken, clubId, diaryDateId);
        res.status(200).json(activities);
    } catch (error) {
        // Fallback-Logging: schreibe Stacktrace in eine Datei, falls STDOUT/STDERR nicht sichtbar ist
        try {
            const msg = `${new Date().toISOString()} - getDiaryDateActivities error: ${error && error.stack ? error.stack : JSON.stringify(error)}\n`;
            fs.appendFileSync('/tmp/diary-activity-error.log', msg);
        } catch (e) {
            // ignore
        }
        devLog(error);
        errorLog(error);
        res.status(500).json({ error: 'Error getting activities' });
    }
}

export const addGroupActivity = async(req, res) => {
    try {
        let userToken = req.headers['authcode'] || req.headers['auth-code'] || null;
        const authHeader = req.headers['authorization'] || req.headers['Authorization'];
        if (!userToken && authHeader && typeof authHeader === 'string' && authHeader.startsWith('Bearer ')) {
            userToken = authHeader.split(' ')[1];
        }
        const { clubId, diaryDateId, groupId, activity, predefinedActivityId, timeblockId, duration, durationText } = req.body;
        const activityItem = await diaryDateActivityService.addGroupActivity(
            userToken,
            clubId,
            diaryDateId,
            groupId,
            activity,
            predefinedActivityId,
            timeblockId,
            duration,
            durationText
        );
        
        // Emit Socket-Event
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (diaryDate?.clubId) {
            emitActivityChanged(diaryDate.clubId, diaryDateId);
        }
        
        res.status(201).json(activityItem);        
    } catch (error) {
        devLog(error);
        res.status(500).json({ error: 'Error adding group activity' });
    }
}

export const updateGroupActivity = async(req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, groupActivityId } = req.params;
        const { predefinedActivityId, duration, durationText, orderId, groupId } = req.body;
        const activityItem = await diaryDateActivityService.updateGroupActivity(
            userToken,
            clubId,
            groupActivityId,
            predefinedActivityId,
            duration,
            durationText,
            orderId,
            groupId
        );
        
        // Emit Socket-Event
        const GroupActivity = (await import('../models/GroupActivity.js')).default;
        const DiaryDateActivity = (await import('../models/DiaryDateActivity.js')).default;
        const groupActivity = await GroupActivity.findByPk(groupActivityId);
        let diaryDateId = null;
        if (groupActivity?.diaryDateActivity) {
            const activity = await DiaryDateActivity.findByPk(groupActivity.diaryDateActivity);
            diaryDateId = activity?.diaryDateId;
        }
        if (diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(diaryDateId);
            if (diaryDate?.clubId) {
                emitActivityChanged(diaryDate.clubId, diaryDateId);
            }
        }
        
        res.status(200).json(activityItem);        
    } catch (error) {
        devLog(error);
        res.status(500).json({ error: 'Error updating group activity' });
    }
}

export const deleteGroupActivity = async(req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, groupActivityId } = req.params;
        
        // Hole diaryDateId vor dem Löschen
        const GroupActivity = (await import('../models/GroupActivity.js')).default;
        const DiaryDateActivity = (await import('../models/DiaryDateActivity.js')).default;
        const groupActivity = await GroupActivity.findByPk(groupActivityId);
        let diaryDateId = null;
        if (groupActivity?.diaryDateActivity) {
            const activity = await DiaryDateActivity.findByPk(groupActivity.diaryDateActivity);
            diaryDateId = activity?.diaryDateId;
        }
        
        await diaryDateActivityService.deleteGroupActivity(userToken, clubId, groupActivityId);
        
        // Emit Socket-Event
        if (diaryDateId) {
            const diaryDate = await DiaryDate.findByPk(diaryDateId);
            if (diaryDate?.clubId) {
                emitActivityChanged(diaryDate.clubId, diaryDateId);
            }
        }
        
        res.status(200).json({ message: 'Group activity deleted' });
    } catch (error) {
        devLog(error);
        res.status(500).json({ error: 'Error deleting group activity' });
    }
}
