const express = require('express');
const DashboardService = require('../services/dashboard');
const { wrapAsync } = require('../helpers');
const db = require('../db/models');
const passport = require('passport');
const router = express.Router();

router.get('/', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const role = req.currentUser.app_role ? req.currentUser.app_role.name : null;
  
  if (role === 'Verified Business Owner') {
    const payload = await DashboardService.getBusinessMetrics(req.currentUser);
    res.status(200).send(payload);
  } else if (role === 'Administrator' || role === 'Platform Owner') {
    const payload = await DashboardService.getAdminMetrics();
    res.status(200).send(payload);
  } else {
    // Default or other roles
    res.status(200).send({
      totalViews: 0,
      activeLeads: 0,
      conversionRate: 0,
    });
  }
}));

router.get('/business-metrics', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const payload = await DashboardService.getBusinessMetrics(req.currentUser);
  res.status(200).send(payload);
}));

router.post('/record-event', (req, res, next) => {
  passport.authenticate('jwt', { session: false }, (err, user) => {
    req.currentUser = user || null;
    next();
  })(req, res, next);
}, wrapAsync(async (req, res) => {
  const { businessId, event_type, metadata } = req.body;
  
  const event = await db.listing_events.create({
    businessId,
    event_type,
    userId: req.currentUser ? req.currentUser.id : null,
    metadata
  });

  res.status(200).send(event);
}));

module.exports = router;