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

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

export const addClub = async (req, res) => {
  console.log('[addClub] - Read out parameters');
  const { authcode: token } = req.headers;
  const { name: clubName } = req.body;

  try {
    console.log('[addClub] - find club by name');
    const club = await ClubService.findClubByName(clubName);
    console.log('[addClub] - get user');
    const user = await getUserByToken(token);
    console.log('[addClub] - check if club already exists');
    if (club) {
      res.status(409).json({ error: "alreadyexists" });
      return;
    }

    console.log('[addClub] - create club');
    const newClub = await ClubService.createClub(clubName);
    console.log('[addClub] - add user to new club');
    await ClubService.addUserToClub(user.id, newClub.id);
    console.log('[addClub] - prepare response');
    res.status(200).json(newClub);
    console.log('[addClub] - done');
  } catch (error) {
    console.log('[addClub] - error');
    console.log(error);
    res.status(500).json({ error: "internalerror" });
  }
};

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

    console.log('[getClub] - get club');
    const club = await ClubService.findClubById(clubId);
    console.log('[getClub] - check club exists');
    if (!club) {
      return res.status(404).json({ message: 'Club not found' });
    }

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

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

  try {
    const user = await getUserByToken(token);
    console.log(user);

    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 {
      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' });
    }
  }
};
