import { Router } from 'express';
import { JoinRequestPayload } from '../cqrs/types';
import {
  getJoinRequestById,
  getServerById,
  updateJoinRequestStatus
} from '../cqrs';
import { notifyUser } from '../websocket/broadcast';
import { resolveServerPermission } from '../services/server-permissions.service';

const router = Router();

router.put('/:id', async (req, res) => {
  const { id } = req.params;
  const { ownerId, status } = req.body;
  const request = await getJoinRequestById(id);

  if (!request)
    return res.status(404).json({ error: 'Request not found' });

  const server = await getServerById(request.serverId);

  if (!server || !ownerId || !resolveServerPermission(server, String(ownerId), 'manageServer'))
    return res.status(403).json({ error: 'Not authorized' });

  await updateJoinRequestStatus(id, status as JoinRequestPayload['status']);

  const updated: JoinRequestPayload = { ...request, status };

  notifyUser(request.userId, { type: 'request_update', request: updated });
  res.json(updated);
});

export default router;
