import type { Request, Response } from 'express';
import CommunicationsService from '@/services/communications';

function routeParam(value: string | string[] | undefined): string {
  if (Array.isArray(value)) return value[0] ?? '';
  return value ?? '';
}

export async function listEvents(req: Request, res: Response): Promise<void> {
  const payload = await CommunicationsService.listEvents(
    req.query,
    req.currentUser,
  );
  res.status(200).send(payload);
}

export async function createEvent(req: Request, res: Response): Promise<void> {
  const payload = await CommunicationsService.createEvent(
    req.body.data,
    req.currentUser,
  );
  res.status(201).send(payload);
}

export async function updateEvent(req: Request, res: Response): Promise<void> {
  const payload = await CommunicationsService.updateEvent(
    routeParam(req.params.id),
    req.body.data,
    req.currentUser,
  );
  res.status(200).send(payload);
}

export async function deleteEvent(req: Request, res: Response): Promise<void> {
  await CommunicationsService.deleteEvent(
    routeParam(req.params.id),
    req.currentUser,
  );
  res.status(204).send();
}

export async function cancelEvent(req: Request, res: Response): Promise<void> {
  const payload = await CommunicationsService.cancelEvent(
    routeParam(req.params.id),
    req.body.data,
    req.currentUser,
  );
  res.status(201).send(payload);
}
