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

export const listMemberGroupPhotos = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const photos = await memberGroupPhotoService.list(userToken, clubId);
    res.status(200).json({ success: true, photos });
  } catch (error) {
    console.error('[listMemberGroupPhotos] error:', error);
    res.status(500).json({ success: false, error: 'Failed to list group photos' });
  }
};

export const createMemberGroupPhoto = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId } = req.params;
    const result = await memberGroupPhotoService.create(userToken, clubId, req.file, req.body);
    res.status(result.status).json(result.response);
  } catch (error) {
    console.error('[createMemberGroupPhoto] error:', error);
    res.status(500).json({ success: false, error: 'Failed to save group photo' });
  }
};

export const updateMemberGroupPhoto = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, photoId } = req.params;
    const result = await memberGroupPhotoService.update(userToken, clubId, photoId, req.body);
    res.status(result.status).json(result.response);
  } catch (error) {
    console.error('[updateMemberGroupPhoto] error:', error);
    res.status(500).json({ success: false, error: 'Failed to update group photo' });
  }
};

export const deleteMemberGroupPhoto = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, photoId } = req.params;
    const result = await memberGroupPhotoService.remove(userToken, clubId, photoId);
    res.status(result.status).json(result.response);
  } catch (error) {
    console.error('[deleteMemberGroupPhoto] error:', error);
    res.status(500).json({ success: false, error: 'Failed to delete group photo' });
  }
};

export const getMemberGroupPhotoImage = async (req, res) => {
  try {
    const { authcode: userToken } = req.headers;
    const { clubId, photoId } = req.params;
    const result = await memberGroupPhotoService.getImage(userToken, clubId, photoId);
    if (result.status === 200) {
      res.setHeader('Content-Type', 'image/jpeg');
      return res.sendFile(result.imagePath);
    }
    return res.status(result.status).json({ success: false, error: result.error });
  } catch (error) {
    console.error('[getMemberGroupPhotoImage] error:', error);
    res.status(500).json({ success: false, error: 'Failed to load group photo' });
  }
};
