import { Request, Response } from 'express';
import { AuthRequest } from '../../../middleware/auth';
import { galleryService } from '../../../services/galleryService';
import { logger } from '../../../config/logger';

export async function createGalleryImage(req: AuthRequest, res: Response) {
  try {
    const { articleId } = req.params;
    const { url, caption, alt, width, height, size, format } = req.body;

    const image = await galleryService.createImage({
      url,
      caption,
      alt,
      width,
      height,
      size,
      format,
      articleId
    });

    res.status(201).json(image);
  } catch (error) {
    logger.error('Ошибка создания изображения в галерее:', error);
    res.status(500).json({ error: 'Сбой создания изображения в галерее' });
  }
}

export async function updateGalleryImage(req: AuthRequest, res: Response) {
  try {
    const { id } = req.params;
    const { caption, alt, order } = req.body;

    const image = await galleryService.updateImage(id, {
      caption,
      alt,
      order
    });

    res.json(image);
  } catch (error) {
    logger.error('Error updating gallery image:', error);
    res.status(500).json({ error: 'Failed to update gallery image' });
  }
}

export async function deleteGalleryImage(req: AuthRequest, res: Response) {
  try {
    const { id } = req.params;
    await galleryService.deleteImage(id);
    res.json({ message: 'Gallery image deleted successfully' });
  } catch (error) {
    logger.error('Error deleting gallery image:', error);
    res.status(500).json({ error: 'Failed to delete gallery image' });
  }
}

export async function reorderGalleryImages(req: AuthRequest, res: Response) {
  try {
    const { articleId } = req.params;
    const { imageIds } = req.body;

    await galleryService.reorderImages(articleId, imageIds);
    res.json({ message: 'Gallery images reordered successfully' });
  } catch (error) {
    logger.error('Error reordering gallery images:', error);
    res.status(500).json({ error: 'Failed to reorder gallery images' });
  }
}

export async function getArticleGallery(req: Request, res: Response) {
  try {
    const { articleId } = req.params;
    const images = await galleryService.getArticleGallery(articleId);
    res.json(images);
  } catch (error) {
    logger.error('Error fetching article gallery:', error);
    res.status(500).json({ error: 'Failed to fetch gallery images' });
  }
}