import DiaryMemberActivity from '../models/DiaryMemberActivity.js';
import DiaryDateActivity from '../models/DiaryDateActivity.js';
import DiaryDates from '../models/DiaryDates.js';
import Participant from '../models/Participant.js';
import { checkAccess } from '../utils/userUtils.js';
import { emitActivityMemberAdded, emitActivityMemberRemoved } from '../services/socketService.js';

export const getMembersForActivity = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, diaryDateActivityId } = req.params;
    await checkAccess(userToken, clubId);
    const list = await DiaryMemberActivity.findAll({ where: { diaryDateActivityId } });
    res.status(200).json(list);
  } catch (e) {
    res.status(500).json({ error: 'Error fetching members for activity' });
  }
};

export const addMembersToActivity = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, diaryDateActivityId } = req.params;
    const { participantIds } = req.body; // array of participant ids
    
    await checkAccess(userToken, clubId);
    
    if (!participantIds || !Array.isArray(participantIds)) {
      console.error('[addMembersToActivity] Invalid participantIds:', participantIds);
      return res.status(400).json({ error: 'participantIds must be an array' });
    }
    
    const validParticipants = await Participant.findAll({ where: { id: participantIds } });
    
    const validIds = new Set(validParticipants.map(p => p.id));
    const created = [];
    
    // Hole clubId und dateId für Events (falls nicht aus params verfügbar)
    const activity = await DiaryDateActivity.findByPk(diaryDateActivityId);
    const diaryDate = activity ? await DiaryDates.findByPk(activity.diaryDateId) : null;
    const eventClubId = diaryDate?.clubId || clubId;
    const dateId = diaryDate?.id || null;
    
    for (const pid of participantIds) {
      if (!validIds.has(pid)) {
        continue;
      }
      const existing = await DiaryMemberActivity.findOne({ where: { diaryDateActivityId, participantId: pid } });
      if (!existing) {
        const rec = await DiaryMemberActivity.create({ diaryDateActivityId, participantId: pid });
        created.push(rec);
        
        // Emit Socket-Event
        if (eventClubId && dateId) {
          emitActivityMemberAdded(eventClubId, diaryDateActivityId, pid, dateId);
        }
      } else {
      }
    }
    res.status(201).json(created);
  } catch (e) {
    console.error('[addMembersToActivity] Error:', e);
    res.status(500).json({ error: 'Error adding members to activity' });
  }
};

export const removeMemberFromActivity = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, diaryDateActivityId, participantId } = req.params;
    await checkAccess(userToken, clubId);
    
    // Hole dateId für Event
    const activity = await DiaryDateActivity.findByPk(diaryDateActivityId);
    const diaryDate = activity ? await DiaryDates.findByPk(activity.diaryDateId) : null;
    const dateId = diaryDate?.id || null;
    
    await DiaryMemberActivity.destroy({ where: { diaryDateActivityId, participantId } });
    
    // Emit Socket-Event
    if (dateId) {
      emitActivityMemberRemoved(clubId, diaryDateActivityId, participantId, dateId);
    }
    
    res.status(200).json({ ok: true });
  } catch (e) {
    res.status(500).json({ error: 'Error removing member from activity' });
  }
};


