import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';
import { uploadFileToR2 } from '../../utils/r2';
import ApiError from '../../utils/apiError';

const prisma = new PrismaClient();

// GET: Fetch all banners (Public or Admin)
export const getBanners = async (req: Request, res: Response) => {
  try {
    const banners = await prisma.featuredBanner.findMany({
      orderBy: { createdAt: 'desc' },
    });
    res.json(banners);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch banners' });
  }
};

// POST: Create a new banner (Admin Only)
export const createBanner = async (req: Request, res: Response) => {
  try {
    const { title, description, cta, link } = req.body;

    // 1. Strict Check: Max 2 Banners
    const count = await prisma.featuredBanner.count();
    if (count >= 2) {
      return res.status(400).json({
        error: 'Limit reached. You can only have 2 active banners. Delete one to add a new one.',
      });
    }

    const imageFile = req.file;

    if (!imageFile) {
      throw new ApiError(false, 400, 'Image is required');
    }

    const uploadImgToR2 = await uploadFileToR2(imageFile);

    if(!uploadImgToR2?.url){
      throw new ApiError(false, 400, 'Image is fail to upload to R2');  
    }

    // 2. Create Banner
    const banner = await prisma.featuredBanner.create({
      data: {
        image: uploadImgToR2.url,
        title,
        description,
        cta,
        link,
      },
    });

    res.status(201).json(banner);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Failed to create banner' });
  }
};

// DELETE: Remove a banner (Admin Only)
export const deleteBanner = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await prisma.featuredBanner.delete({ where: { id } });
    res.json({ message: 'Banner deleted successfully' });
  } catch (error) {
    res.status(500).json({ error: 'Failed to delete banner' });
  }
};
