import { checkAccess } from '../utils/userUtils.js';
import officialTournamentService from '../services/officialTournamentService.js';
import clickTtTournamentRegistrationService from '../services/clickTtTournamentRegistrationService.js';

export const updateOfficialTournament = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id } = req.params;
    await checkAccess(userToken, clubId);

    const result = await officialTournamentService.updateOfficialTournament(clubId, id, req.body);
    if (!result) return res.status(404).json({ error: 'not found' });
    res.status(200).json(result);
  } catch (e) {
    console.error('[updateOfficialTournament] Error:', e);
    res.status(500).json({ error: 'Failed to update tournament' });
  }
};

export const uploadTournamentPdf = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    await checkAccess(userToken, clubId);
    if (!req.file || !req.file.buffer) return res.status(400).json({ error: 'No pdf provided' });

    const result = await officialTournamentService.uploadTournamentPdf(clubId, req.file.buffer);
    res.status(201).json(result);
  } catch (e) {
    console.error('[uploadTournamentPdf] Error:', e);
    res.status(500).json({ error: 'Failed to parse pdf' });
  }
};

export const getParsedTournament = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id } = req.params;
    await checkAccess(userToken, clubId);

    const result = await officialTournamentService.getParsedTournament(clubId, id);
    if (!result) return res.status(404).json({ error: 'not found' });
    res.status(200).json(result);
  } catch (e) {
    res.status(500).json({ error: 'Failed to fetch parsed tournament' });
  }
};

export const upsertCompetitionMember = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id } = req.params;
    await checkAccess(userToken, clubId);

    const result = await officialTournamentService.upsertCompetitionMember(id, req.body);
    return res.status(200).json(result);
  } catch (e) {
    console.error('[upsertCompetitionMember] Error:', e);
    if (e?.status) return res.status(e.status).json({ error: e.message });
    res.status(500).json({ error: 'Failed to save participation' });
  }
};

export const updateParticipantStatus = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id } = req.params;
    await checkAccess(userToken, clubId);

    const result = await officialTournamentService.updateParticipantStatus(id, req.body);
    return res.status(200).json(result);
  } catch (e) {
    console.error('[updateParticipantStatus] Error:', e);
    if (e?.status) return res.status(e.status).json({ error: e.message });
    res.status(500).json({ error: 'Failed to update participant status' });
  }
};

export const listOfficialTournaments = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    await checkAccess(userToken, clubId);

    const list = await officialTournamentService.listOfficialTournaments(clubId);
    res.status(200).json(list);
  } catch (e) {
    console.error('[listOfficialTournaments] Error:', e);
    const errorMessage = e.message || 'Failed to list tournaments';
    res.status(e.statusCode || 500).json({ error: errorMessage });
  }
};

export const listClubParticipations = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    await checkAccess(userToken, clubId);

    const out = await officialTournamentService.listClubParticipations(clubId);
    res.status(200).json(out);
  } catch (e) {
    res.status(500).json({ error: 'Failed to list club participations' });
  }
};

export const deleteOfficialTournament = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id } = req.params;
    await checkAccess(userToken, clubId);

    const deleted = await officialTournamentService.deleteOfficialTournament(clubId, id);
    if (!deleted) return res.status(404).json({ error: 'not found' });
    res.status(204).send();
  } catch (e) {
    res.status(500).json({ error: 'Failed to delete tournament' });
  }
};

export const autoRegisterOfficialTournamentParticipants = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, id: tournamentId } = req.params;
    const userId = req.user?.id;

    const result = await clickTtTournamentRegistrationService.autoRegisterPendingParticipants({
      userToken,
      userId,
      clubId,
      tournamentId
    });

    res.status(200).json(result);
  } catch (e) {
    console.error('[autoRegisterOfficialTournamentParticipants] Error:', e);
    res.status(e.statusCode || e.status || 500).json({
      success: false,
      error: e.message || 'Teilnehmer konnten nicht automatisch in click-TT angemeldet werden'
    });
  }
};
