import { Router, Response, NextFunction } from 'express';
import { body, validationResult } from 'express-validator';
import prisma from '../lib/prisma';
import { authenticate, requireRole, AuthRequest } from '../middleware/auth';

const router = Router();

// GET /api/streams — public
function mapStream(s: any) {
  return {
    id: s.id,
    name: s.name,
    location: s.camera_location,
    status: s.status,
    viewerCount: 0,
    hlsUrl: s.stream_url,
    thumbnailUrl: s.thumbnail_url,
    createdAt: s.created_at,
  };
}

router.get('/', async (_req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const streams = await prisma.livestreamSource.findMany({ orderBy: { status: 'asc' } });
    res.json(streams.map(mapStream));
  } catch (err) { next(err); }
});

// GET /api/streams/:id — public
router.get('/:id', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const stream = await prisma.livestreamSource.findUnique({ where: { id: req.params.id } });
    if (!stream) { res.status(404).json({ error: 'Stream not found' }); return; }
    res.json(mapStream(stream));
  } catch (err) { next(err); }
});

// POST /api/streams — admin only
router.post('/', authenticate, requireRole('admin'),
  [
    body('name').trim().notEmpty(),
    body('stream_url').isURL(),
    body('camera_location').trim().notEmpty(),
    body('status').optional().isIn(['live', 'offline']),
  ],
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) { res.status(422).json({ errors: errors.array() }); return; }
    try {
      const { name, stream_url, camera_location, status, thumbnail_url } = req.body;
      const stream = await prisma.livestreamSource.create({
        data: { name, stream_url, camera_location, status: status || 'offline', thumbnail_url },
      });
      res.status(201).json(stream);
    } catch (err) { next(err); }
  }
);

// PATCH /api/streams/:id — admin only
router.patch('/:id', authenticate, requireRole('admin'),
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { name, stream_url, camera_location, status, thumbnail_url } = req.body;
      const updated = await prisma.livestreamSource.update({
        where: { id: req.params.id },
        data: { name, stream_url, camera_location, status, thumbnail_url },
      });
      res.json(updated);
    } catch (err) { next(err); }
  }
);

// DELETE /api/streams/:id — admin only
router.delete('/:id', authenticate, requireRole('admin'),
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      await prisma.livestreamSource.delete({ where: { id: req.params.id } });
      res.json({ message: 'Stream deleted' });
    } catch (err) { next(err); }
  }
);

export default router;
