import clubVenueService from '../services/clubVenueService.js';

const handleError = (res, label, error) => {
  if (error.message === 'noaccess') return res.status(403).json({ error: 'noaccess' });
  if (error.statusCode || error.status) return res.status(error.statusCode || error.status).json({ error: error.message });
  console.error(`[${label}] - error:`, error);
  return res.status(500).json({ error: 'internalerror' });
};

export const listClubVenues = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubId } = req.params;
    const venues = await clubVenueService.list(token, clubId);
    res.status(200).json(venues);
  } catch (error) {
    handleError(res, 'listClubVenues', error);
  }
};

export const createClubVenue = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubId } = req.params;
    const venue = await clubVenueService.create(token, clubId, req.body);
    res.status(201).json(venue);
  } catch (error) {
    handleError(res, 'createClubVenue', error);
  }
};

export const updateClubVenue = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubId, venueId } = req.params;
    const venue = await clubVenueService.update(token, clubId, venueId, req.body);
    res.status(200).json(venue);
  } catch (error) {
    handleError(res, 'updateClubVenue', error);
  }
};

export const deleteClubVenue = async (req, res) => {
  try {
    const { authcode: token } = req.headers;
    const { clubId, venueId } = req.params;
    const result = await clubVenueService.delete(token, clubId, venueId);
    res.status(200).json(result);
  } catch (error) {
    handleError(res, 'deleteClubVenue', error);
  }
};
