import { Router, Request, Response, NextFunction } from 'express';
import { blocksService } from './blocks.service';
import { createPageBlockSchema, updatePageBlockSchema, listPageBlocksSchema } from './pages.schemas';
import { validate } from '../../middleware/validate';
import { authenticate } from '../../middleware/auth.middleware';
import { requireRole } from '../../middleware/rbac.middleware';
import { CONTENT_ROLES } from '../../utils/roles';

const router = Router();

router.use(authenticate);
router.use(requireRole(...CONTENT_ROLES));

// GET /api/page-blocks — list all blocks
router.get(
  '/',
  validate(listPageBlocksSchema, 'query'),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const blocks = await blocksService.findAll(req.query as any);
      res.json(blocks);
    } catch (err) {
      next(err);
    }
  }
);

// GET /api/page-blocks/:id — get single block
router.get(
  '/:id',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const block = await blocksService.findById(id);
      res.json(block);
    } catch (err) {
      next(err);
    }
  }
);

// POST /api/page-blocks — create block
router.post(
  '/',
  validate(createPageBlockSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const block = await blocksService.create(req.body);
      res.status(201).json(block);
    } catch (err) {
      next(err);
    }
  }
);

// PUT /api/page-blocks/:id — update block
router.put(
  '/:id',
  validate(updatePageBlockSchema),
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      const block = await blocksService.update(id, req.body);
      res.json(block);
    } catch (err) {
      next(err);
    }
  }
);

// DELETE /api/page-blocks/:id — delete block
router.delete(
  '/:id',
  async (req: Request, res: Response, next: NextFunction) => {
    try {
      const id = req.params.id as string;
      await blocksService.delete(id);
      res.status(204).send();
    } catch (err) {
      next(err);
    }
  }
);

export { router as blocksRouter };
