import { Request, Response } from 'express';
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

// GET /api/admin/announcements
export const getAnnouncements = async (req: Request, res: Response) => {
  try {
    const announcements = await prisma.announcement.findMany({
      orderBy: { createdAt: 'desc' },
    });
    res.json(announcements);
  } catch (error) {
    console.error("Get Announcements Error:", error);
    res.status(500).json({ error: "Failed to fetch announcements" });
  }
};

// POST /api/admin/announcements
export const createAnnouncement = async (req: Request, res: Response) => {
  try {
    const { text, isActive } = req.body;

    if (!text) {
      return res.status(400).json({ error: "Announcement text is required" });
    }

    const newAnnouncement = await prisma.announcement.create({
      data: {
        text,
        isActive: isActive !== undefined ? isActive : true,
      },
    });

    res.status(201).json(newAnnouncement);
  } catch (error) {
    console.error("Create Announcement Error:", error);
    res.status(500).json({ error: "Failed to create announcement" });
  }
};

// PUT /api/admin/announcements/:id
export const updateAnnouncement = async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { text, isActive } = req.body;

    const updated = await prisma.announcement.update({
      where: { id },
      data: {
        text,
        isActive,
      },
    });

    res.json(updated);
  } catch (error) {
    console.error("Update Announcement Error:", error);
    res.status(500).json({ error: "Failed to update announcement" });
  }
};

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