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

const router = Router();

router.use(requireAuth, requireRole('customer'));

router.get('/', async (req, res) => {
  const rows = await Vehicle.findAll({
    where: { user_id: req.user.id },
    order: [['id', 'DESC']],
    raw: true,
  });
  return res.json({ vehicles: rows });
});

router.post('/', async (req, res) => {
  const { type, brand, model, number_plate } = req.body || {};
  if (!brand || !model || !number_plate) {
    return sendError(
      res,
      400,
      'VALIDATION_ERROR',
      'brand, model, number_plate are required'
    );
  }
  const vehicle = await Vehicle.create({
    user_id: req.user.id,
    type: String(type || 'car'),
    brand: String(brand),
    model: String(model),
    number_plate: String(number_plate),
  });
  return res.status(201).json({ vehicle });
});

router.put('/:id', async (req, res) => {
  const id = Number(req.params.id);
  const { type, brand, model, number_plate } = req.body || {};
  const cur = await Vehicle.findOne({ where: { id, user_id: req.user.id } });
  if (!cur) {
    return sendError(res, 404, 'NOT_FOUND', 'Vehicle not found');
  }
  cur.type = type != null ? String(type) : cur.type;
  cur.brand = brand != null ? String(brand) : cur.brand;
  cur.model = model != null ? String(model) : cur.model;
  cur.number_plate =
    number_plate != null ? String(number_plate) : cur.number_plate;
  await cur.save();
  return res.json({ vehicle: cur });
});

router.delete('/:id', async (req, res) => {
  const id = Number(req.params.id);
  const deleted = await Vehicle.destroy({ where: { id, user_id: req.user.id } });
  if (deleted === 0) {
    return sendError(res, 404, 'NOT_FOUND', 'Vehicle not found');
  }
  return res.json({ ok: true });
});

export default router;
