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

const prisma = new PrismaClient();

// GET /api/admin/banners
export const getBanners = async (req: Request, res: Response) => {
  try {
    const banners = await prisma.banner.findMany({
      orderBy: { order: 'asc' }, // Sort by display order
    });
    res.json(banners);
  } catch (error) {
    console.error("Get Banners Error:", error);
    res.status(500).json({ error: "Failed to fetch banners" });
  }
};

// POST /api/admin/banners
export const createBanner = async (req: Request, res: Response) => {
  try {
    const { title, link, buttonText, active, order } = req.body;

    if (!title  || !link) {
      return res.status(400).json({ error: "Title, Image URL, and Link are required" });
    }

    const imageFile=req.file;

    if(!imageFile.path){
     throw new ApiError(false,400,"Images is required")
    }

    const uploadtoR2=await uploadFileToR2(imageFile);

    const newBanner = await prisma.banner.create({
      data: {
        title,
        image:uploadtoR2.url,
        link,
        buttonText: buttonText || "Shop Now", // Default if empty
        active:  active==="true",
        order: order ? parseInt(order) : 0,
      },
    });

    res.status(201).json(newBanner);
  } catch (error) {
    console.error("Create Banner Error:", error);
    res.status(500).json({ error: "Failed to create banner" });
  }
};

// PUT /api/admin/banners/:id
export const updateBanner = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { title, image, link, buttonText, active, order } = req.body;

    const updatedBanner = await prisma.banner.update({
      where: { id },
      data: {
        title,
        image,
        link,
        buttonText,
        active,
        order: order ? parseInt(order) : undefined,
      },
    });

    res.json(updatedBanner);
  } catch (error) {
    console.error("Update Banner Error:", error);
    res.status(500).json({ error: "Failed to update banner" });
  }
};

// DELETE /api/admin/banners/:id
export const deleteBanner = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    await prisma.banner.delete({ where: { id } });
    res.json({ message: "Banner deleted successfully" });
  } catch (error) {
    console.error("Delete Banner Error:", error);
    res.status(500).json({ error: "Failed to delete banner" });
  }
};