import { Router } from 'express';
import { Service } from '../models/index.js';
import { requireAuth, requireRole } from '../middleware/auth.js';
import { sendError } from '../util/httpError.js';

const router = Router();

router.get('/', async (_req, res) => {
  const rows = await Service.findAll({
    attributes: ['id', 'name', 'price'],
    order: [['name', 'ASC']],
    raw: true,
  });
  return res.json({ services: rows });
});

router.post('/', requireAuth, requireRole('admin', 'super_admin'), async (req, res) => {
  const { name, price } = req.body || {};
  if (!name || price == null) {
    return sendError(res, 400, 'VALIDATION_ERROR', 'name and price required');
  }
  const service = await Service.create({
    name: String(name),
    price: Number(price),
  });
  return res.status(201).json({ service });
});

export default router;
