import { Router } from 'express';
import type { Request, Response } from 'express';
import { authenticate } from '../../middleware/auth.middleware';
import { socialActionRateLimit } from './social.rate-limits';
import { blockService } from './block.service';
import { checkSocialEnabled } from './social.middleware';
import { z } from 'zod';

const blockUserSchema = z.object({
  userId: z.string().cuid(),
});

const router = Router();
router.use(authenticate);
router.use(checkSocialEnabled);

/** POST /api/social/blocks — block a user */
router.post('/', socialActionRateLimit, async (req: Request, res: Response) => {
  try {
    const { userId } = blockUserSchema.parse(req.body);
    const result = await blockService.blockUser(req.user!.id, userId);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'BLOCK_ERROR' } });
  }
});

/** DELETE /api/social/blocks/:userId — unblock a user */
router.delete('/:userId', async (req: Request, res: Response) => {
  try {
    const blockedUserId = req.params.userId as string;
    const result = await blockService.unblockUser(req.user!.id, blockedUserId);
    res.json(result);
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'UNBLOCK_ERROR' } });
  }
});

/** GET /api/social/blocks — list blocked users */
router.get('/', async (req: Request, res: Response) => {
  try {
    const blocked = await blockService.listBlocked(req.user!.id);
    res.json({ blocked });
  } catch (err: any) {
    res.status(err.statusCode || 500).json({ error: { message: err.message, code: 'BLOCKS_LIST_ERROR' } });
  }
});

export { router as blockRouter };
