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';
import { getAuthenticatedUserId, requireAuth } from '../middleware/require-auth';

const router = Router();

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

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

  if (ownerId && ownerId !== authenticatedUserId) {
    return res.status(400).json({
      error: 'ownerId must match the authenticated user',
      errorCode: 'USER_ID_MISMATCH'
    });
  }

  const server = await getServerById(request.serverId);

  if (!server || !resolveServerPermission(server, authenticatedUserId, '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;
