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

const router = Router();

// GET /api/burrows — public
router.get('/', optionalAuth, async (_req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const burrows = await prisma.burrow.findMany({
      include: { assigned_volunteer: { select: { id: true, name: true } } },
      orderBy: { created_at: 'desc' },
    });
    res.json(burrows);
  } catch (err) { next(err); }
});

// GET /api/burrows/:id — public
router.get('/:id', async (req: AuthRequest, res: Response, next: NextFunction) => {
  try {
    const burrow = await prisma.burrow.findUnique({
      where: { id: req.params.id },
      include: { assigned_volunteer: { select: { id: true, name: true } } },
    });
    if (!burrow) { res.status(404).json({ error: 'Burrow not found' }); return; }
    res.json(burrow);
  } catch (err) { next(err); }
});

// POST /api/burrows — admin or volunteer
router.post('/',
  authenticate, requireRole('admin', 'volunteer'),
  [
    body('gps_lat').isFloat({ min: -90, max: 90 }),
    body('gps_lng').isFloat({ min: -180, max: 180 }),
    body('status').optional().isIn(['active', 'inactive', 'destroyed']),
  ],
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) { res.status(422).json({ errors: errors.array() }); return; }
    try {
      const { gps_lat, gps_lng, status, location_description, assigned_volunteer_id, photos } = req.body;
      const burrow = await prisma.burrow.create({
        data: { gps_lat, gps_lng, status, location_description, assigned_volunteer_id, photos: photos || [] },
      });
      res.status(201).json(burrow);
    } catch (err) { next(err); }
  }
);

// PATCH /api/burrows/:id — admin or volunteer
router.patch('/:id', authenticate, requireRole('admin', 'volunteer'),
  async (req: AuthRequest, res: Response, next: NextFunction) => {
    try {
      const { gps_lat, gps_lng, status, location_description, assigned_volunteer_id, photos } = req.body;
      const burrow = await prisma.burrow.update({
        where: { id: req.params.id },
        data: { gps_lat, gps_lng, status, location_description, assigned_volunteer_id, photos },
      });
      res.json(burrow);
    } catch (err) { next(err); }
  }
);

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

export default router;
