import { Router } from 'express';
import { Op, fn, col } from 'sequelize';
import { Booking, JobCard, User, Service } from '../models/index.js';
import { requireAuth, requireRole } from '../middleware/auth.js';

const router = Router();

router.get('/stats', requireAuth, requireRole('admin', 'super_admin'), async (_req, res) => {
  const bookings_total = await Booking.count();
  const bookings_active = await Booking.count({
    where: { status: { [Op.in]: ['pending', 'confirmed', 'in_progress'] } },
  });
  const rev = await JobCard.findOne({
    attributes: [[fn('COALESCE', fn('SUM', col('estimated_cost')), 0), 'revenue_estimated']],
    raw: true,
  });
  return res.json({
    bookings_total: Number(bookings_total || 0),
    bookings_active: Number(bookings_active || 0),
    revenue_estimated: Number(rev?.revenue_estimated || 0),
  });
});

// Super Admin: List all users
router.get('/users', requireAuth, requireRole('super_admin'), async (_req, res) => {
  const users = await User.findAll({
    order: [['created_at', 'DESC']],
  });
  return res.json({ users });
});

// Super Admin: Update user role
router.patch('/users/:id/role', requireAuth, requireRole('super_admin'), async (req, res) => {
  const { role } = req.body;
  if (!['customer', 'employee', 'admin', 'super_admin'].includes(role)) {
    return res.status(400).json({ error: { code: 'INVALID_ROLE', message: 'Invalid role' } });
  }
  const user = await User.findByPk(req.params.id);
  if (!user) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'User not found' } });
  
  user.role = role;
  await user.save();
  return res.json({ user });
});

// Super Admin: Platform Summary
router.get('/platform-summary', requireAuth, requireRole('super_admin'), async (_req, res) => {
  const userCount = await User.count();
  const serviceCount = await Service.count();
  const totalRevenue = await JobCard.sum('final_cost') || 0;
  return res.json({
    total_users: userCount,
    total_services: serviceCount,
    total_revenue: totalRevenue,
  });
});

export default router;
