const db = require('../config/db');
const axios = require('axios');

async function getCardImage(req, res) {
  const { cardId } = req.params;
  const { imageId } = req.query;

  try {
    const [rows] = imageId
      ? await db.execute(
          'SELECT image_id, image_data, image_url FROM card_images WHERE card_id = ? AND image_id = ? LIMIT 1',
          [cardId, imageId]
        )
      : await db.execute(
          'SELECT image_id, image_data, image_url FROM card_images WHERE card_id = ? LIMIT 1',
          [cardId]
        );

    if (rows.length === 0) {
      return res.status(404).json({ error: 'Card image not found' });
    }

    const cardImage = rows[0];

    if (cardImage.image_data) {
      const base64Image = cardImage.image_data.toString('base64');
      return res.json({ image: `data:image/png;base64,${base64Image}` });
    }

    if (!cardImage.image_url) {
      return res.status(404).json({ error: 'No image URL available for this card' });
    }

    const response = await axios.get(cardImage.image_url, { responseType: 'arraybuffer' });
    const imageBuffer = Buffer.from(response.data, 'binary');

    await db.execute(
      'UPDATE card_images SET image_data = ? WHERE image_id = ?',
      [imageBuffer, cardImage.image_id]
    );

    const base64Image = imageBuffer.toString('base64');
    res.json({ image: `data:image/png;base64,${base64Image}` });
  } catch (err) {
    console.error('Error fetching card image:', err);
    res.status(500).json({ error: 'Failed to fetch card image' });
  }
}

module.exports = { getCardImage };
