import ClubService from '../services/clubService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';

export const getClubs = async (req, res) => {
  try {
    const clubs = await ClubService.getAllClubs();
    res.status(200).json(clubs);
  } catch (error) {
    console.error('[getClubs] - error:', error);
    res.status(500).json({ error: "internalerror" });
  }
};

export const addClub = async (req, res) => {
  const { authcode: token } = req.headers;
  const { name: clubName } = req.body;

  try {
    const club = await ClubService.findClubByName(clubName);
    const user = await getUserByToken(token);
    if (club) {
      res.status(409).json({ error: "alreadyexists" });
      return;
    }

    const newClub = await ClubService.createClub(clubName);
    await ClubService.addUserToClub(user.id, newClub.id, true); // true = isOwner
    res.status(200).json(newClub);
  } catch (error) {
    console.error('[addClub] - error:', error);
    res.status(500).json({ error: "internalerror" });
  }
};

export const getClub = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubid: clubId } = req.params;
    const user = await getUserByToken(token);
    const access = await ClubService.getUserClubAccess(user.id, clubId);
    if (access.length === 0 || !access[0].approved) {
      res.status(403).json({ error: "noaccess", status: access.length === 0 ? "notrequested" : "requested" });
      return;
    }

    const club = await ClubService.findClubById(clubId);
    if (!club) {
      return res.status(404).json({ message: 'Club not found' });
    }

    res.status(200).json(club);
  } catch (error) {
    console.error('[getClub] - error:', error);
    res.status(500).json({ message: 'Server error' });
  }
};

export const updateClubSettings = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubid } = req.params;
    const {
      greetingText,
      associationMemberNumber,
      myTischtennisFedNickname,
      autoFetchRankings,
      countryCode,
      stateCode,
      memberDataQualityRequirements,
      feeRules,
      outgoingInvoicePrefix,
      outgoingInvoiceNextNumber,
      incomingInvoicePrefix,
      incomingInvoiceNextNumber
    } = req.body;
    const updated = await ClubService.updateClubSettings(token, clubid, {
      greetingText,
      associationMemberNumber,
      myTischtennisFedNickname,
      autoFetchRankings,
      countryCode,
      stateCode,
      memberDataQualityRequirements,
      feeRules,
      outgoingInvoicePrefix,
      outgoingInvoiceNextNumber,
      incomingInvoicePrefix,
      incomingInvoiceNextNumber
    });
    res.status(200).json(updated);
  } catch (error) {
    if (error.message === 'noaccess') {
      res.status(403).json({ error: 'noaccess' });
    } else if (error.message === 'clubnotfound') {
      res.status(404).json({ error: 'clubnotfound' });
    } else {
      console.error('[updateClubSettings] - error:', error);
      res.status(500).json({ error: 'internalerror' });
    }
  }
};

export const requestClubAccess = async (req, res) => {
  const { authcode: token } = req.headers;
  const { clubid: clubId } = req.params;

  try {
    const user = await getUserByToken(token);

    await ClubService.requestAccessToClub(user.id, clubId);
    res.status(200).json({});
  } catch (error) {
    if (error.message === 'alreadyrequested') {
      res.status(409).json({ err: "alreadyrequested" });
    } else if (error.message === 'clubnotfound') {
      res.status(404).json({ err: "clubnotfound" });
    } else {
      console.error('[requestClubAccess] - error:', error);
      res.status(500).json({ err: "internalerror" });
    }
  }
};

export const approveClubAccess = async (req, res) => {
  const { authcode: token } = req.headers;
  const { clubid: clubId, userid: toApproveUserId } = req.body;
  try {
    await ClubService.approveUserClubAccess(token, clubId, toApproveUserId);
    res.status(200).json({ status: 'approved' });
  } catch (error) {
    if (error.message === 'norequest') {
      res.status(404).json({ error: 'norequest' });
    } else if (error.message === 'noaccess') {
      res.status(403).json({ error: 'noaccess' });
    } else {
      res.status(500).json({ error: 'internalerror' });
    }
  }
};

export const rejectClubAccess = async (req, res) => {
  const { authcode: token } = req.headers;
  const { clubid: clubId, userid: toRejectUserId } = req.body;
  try {
    await ClubService.rejectUserClubAccess(token, clubId, toRejectUserId);
    res.status(200).json({ status: 'rejected' });
  } catch (error) {
    if (error.message === 'norequest') {
      res.status(404).json({ error: 'norequest' });
    } else if (error.message === 'noaccess') {
      res.status(403).json({ error: 'noaccess' });
    } else {
      res.status(500).json({ error: 'internalerror' });
    }
  }
};

export const getPendingApprovals = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubid: clubId } = req.params;
    const pendingApprovals = await ClubService.getPendingUserApprovals(token, clubId);
    res.status(200).json(pendingApprovals);
  } catch (error) {
    console.error('[getPendingApprovals] - Error:', error);
    if (error.message === 'noaccess') {
      res.status(403).json({ error: 'noaccess' });
    } else {
      res.status(500).json({ error: 'internalerror' });
    }
  }
};
