import { Request, Response } from 'express';
import { prisma } from '../../../lib/prisma';

export async function getActiveAnnouncement(req: Request, res: Response) {
  try {
    const announcement = await prisma.announcement.findFirst({
      where: { isActive: true },
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        message: true
      }
    });

    if (!announcement) {
      return res.status(204).send();
    }

    res.json(announcement);
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
}

export async function createAnnouncement(req: Request, res: Response) {
  try {
    const { message } = req.body;

    if (!message || typeof message !== 'string' || message.trim().length === 0) {
      return res.status(400).json({ error: 'Message is required' });
    }

    const announcement = await prisma.announcement.create({
      data: {
        message: message.trim()
      }
    });

    res.status(201).json(announcement);
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
}

export async function updateAnnouncement(req: Request, res: Response) {
  try {
    const { id } = req.params;
    const { message, isActive } = req.body;

    const announcement = await prisma.announcement.update({
      where: { id },
      data: {
        ...(message && { message: message.trim() }),
        ...(typeof isActive === 'boolean' && { isActive })
      }
    });

    res.json(announcement);
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
}

export async function deleteAnnouncement(req: Request, res: Response) {
  try {
    const { id } = req.params;

    await prisma.announcement.delete({
      where: { id }
    });

    res.status(204).send();
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
}

export async function getAllAnnouncements(req: Request, res: Response) {
  try {
    const announcements = await prisma.announcement.findMany({
      orderBy: { createdAt: 'desc' }
    });

    res.json(announcements);
  } catch (error) {
    res.status(500).json({ error: 'Server error' });
  }
}
