import friendlyMatchSharedService from '../services/friendlyMatchSharedService.js';
import {
  emitFriendlySharedMatchDeleted,
  emitFriendlySharedMatchUpdated,
} from '../services/socketService.js';

function userTokenFrom(req) {
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.slice(7);
  }
  return req.headers.authcode || authHeader;
}

export const findSharedFriendlyMatches = async (req, res) => {
  try {
    const { clubId, name, date, startTime } = req.query;
    const matches = await friendlyMatchSharedService.findByNameDateStartTime(userTokenFrom(req), clubId, {
      name,
      date,
      startTime,
    });
    res.status(200).json(matches);
  } catch (error) {
    console.error('[findSharedFriendlyMatches] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Suche nach Freundschaftsspielen fehlgeschlagen.' });
  }
};

export const listSharedFriendlyMatches = async (req, res) => {
  try {
    const data = await friendlyMatchSharedService.listShared(userTokenFrom(req), req.params.clubId);
    res.status(200).json(data);
  } catch (error) {
    console.error('[listSharedFriendlyMatches] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Gemeinsame Freundschaftsspiele konnten nicht geladen werden.' });
  }
};

export const getSharedFriendlyMatchMembers = async (req, res) => {
  try {
    const members = await friendlyMatchSharedService.membersForSide(
      userTokenFrom(req),
      req.params.clubId,
      req.params.matchId,
      req.params.side,
    );
    res.status(200).json(members);
  } catch (error) {
    console.error('[getSharedFriendlyMatchMembers] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Mitglieder konnten nicht geladen werden.' });
  }
};

export const updateSharedFriendlyMatch = async (req, res) => {
  try {
    const match = await friendlyMatchSharedService.updateShared(
      userTokenFrom(req),
      req.params.clubId,
      req.params.matchId,
      req.body,
    );
    emitFriendlySharedMatchUpdated(match.homeClubId, match.guestClubId, match);
    res.status(200).json(match);
  } catch (error) {
    console.error('[updateSharedFriendlyMatch] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Gemeinsames Freundschaftsspiel konnte nicht gespeichert werden.' });
  }
};

export const updateSharedFriendlyMatchPlayers = async (req, res) => {
  try {
    const match = await friendlyMatchSharedService.updateSharedPlayers(
      userTokenFrom(req),
      req.params.clubId,
      req.params.matchId,
      req.body,
    );
    emitFriendlySharedMatchUpdated(match.homeClubId, match.guestClubId, match);
    res.status(200).json({ message: 'Teilnehmer gespeichert', data: match });
  } catch (error) {
    console.error('[updateSharedFriendlyMatchPlayers] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Teilnehmer konnten nicht gespeichert werden.' });
  }
};

export const deleteSharedFriendlyMatch = async (req, res) => {
  try {
    const match = await friendlyMatchSharedService.getSharedById(
      userTokenFrom(req),
      req.params.clubId,
      req.params.matchId,
    );
    const result = await friendlyMatchSharedService.removeShared(userTokenFrom(req), req.params.clubId, req.params.matchId);
    emitFriendlySharedMatchDeleted(match.homeClubId, match.guestClubId, Number(req.params.matchId));
    res.status(200).json(result);
  } catch (error) {
    console.error('[deleteSharedFriendlyMatch] Error:', error);
    res.status(error.statusCode || 500).json({ error: error.message || 'Gemeinsames Freundschaftsspiel konnte nicht geloescht werden.' });
  }
};
