const asyncHandler = require('../middlewares/asyncHandler');
const { getLocationFilterFromRequest } = require('../utils/auditFilterHelper');
const {
  getDashboardStats,
  getAuditsWithRpnInRange,
  getAuditsWithTotalRpnInBucket,
  getAuditTrends,
  getSeverityOfHarmDistribution,
  getLikelihoodOfHarmDistribution,
  getRpnAuditCounts,
  getObservationOpenClosedCounts,
  getObservationOpenClosedList,
  getSioOioCaStats,
  getSioOioCaList,
  getAuditsBySeverityOfHarm,
  getAuditsByLikelihoodOfHarm,
} = require('../repositories/dashboardRepository');

exports.getDashboardStats = asyncHandler(async (req, res) => {
  const period = req.query.period; // 'week' | 'month' | 'year'
  const filter = getLocationFilterFromRequest(req);
  const stats = await getDashboardStats(period, filter);
  res.status(200).json({ success: true, data: stats });
});

exports.getCriticalFindingsAudits = asyncHandler(async (req, res) => {
  const filter = getLocationFilterFromRequest(req);
  const sat_audits = await getAuditsWithRpnInRange(32, 128, filter);
  res.status(200).json({ success: true, data: sat_audits });
});

exports.getAuditTrends = asyncHandler(async (req, res) => {
  const year = req.query.year ? parseInt(req.query.year, 10) : new Date().getFullYear();
  const period = req.query.period || 'monthly'; // 'daily' | 'monthly' | 'quarterly' | 'yearly'
  const filter = getLocationFilterFromRequest(req);
  const data = await getAuditTrends(year, period, filter);
  res.status(200).json({ success: true, data });
});

exports.getHarmDistributions = asyncHandler(async (req, res) => {
  const filter = getLocationFilterFromRequest(req);
  const [severityOfHarm, likelihoodOfHarm] = await Promise.all([
    getSeverityOfHarmDistribution(filter),
    getLikelihoodOfHarmDistribution(filter),
  ]);
  res.status(200).json({
    success: true,
    data: { severityOfHarm, likelihoodOfHarm },
  });
});

exports.getRpnAuditCounts = asyncHandler(async (req, res) => {
  const filter = getLocationFilterFromRequest(req);
  const data = await getRpnAuditCounts(filter);
  res.status(200).json({ success: true, data });
});

exports.getAuditsByRpnValue = asyncHandler(async (req, res) => {
  const rpnValue = parseInt(req.params.rpnValue, 10);
  const validValues = [1, 2, 4, 8, 16, 32, 64, 128];
  if (!Number.isInteger(rpnValue) || !validValues.includes(rpnValue)) {
    return res.status(400).json({ success: false, message: 'Invalid RPN value. Use one of: 1, 2, 4, 8, 16, 32, 64, 128' });
  }
  const filter = getLocationFilterFromRequest(req);
  const sat_audits = await getAuditsWithTotalRpnInBucket(rpnValue, filter);
  res.status(200).json({ success: true, data: sat_audits });
});

exports.getObservationOpenClosedCounts = asyncHandler(async (req, res) => {
  const period = req.query.period || 'all';
  const filter = getLocationFilterFromRequest(req);
  const data = await getObservationOpenClosedCounts({ period }, filter);
  res.status(200).json({ success: true, data });
});

exports.getObservationOpenClosedList = asyncHandler(async (req, res) => {
  const period = req.query.period || 'all';
  const filter = getLocationFilterFromRequest(req);
  const data = await getObservationOpenClosedList({ period }, filter);
  res.status(200).json({ success: true, data });
});

exports.getSioOioCaStats = asyncHandler(async (req, res) => {
  const filter = getLocationFilterFromRequest(req);
  const data = await getSioOioCaStats(filter);
  res.status(200).json({ success: true, data });
});

exports.getSioOioCaList = asyncHandler(async (req, res) => {
  const type = req.query.type || '';
  const validTypes = ['SIO', 'OIO', 'CA', 'SIO_CLOSED'];
  if (!validTypes.includes(String(type).trim().toUpperCase())) {
    return res.status(400).json({ success: false, message: 'Invalid type. Use one of: SIO, OIO, CA, SIO_CLOSED' });
  }
  const filter = getLocationFilterFromRequest(req);
  const data = await getSioOioCaList(type, filter);
  res.status(200).json({ success: true, data });
});

exports.getAuditsBySeverityOfHarm = asyncHandler(async (req, res) => {
  const severity = req.query.severity || null;
  const filter = getLocationFilterFromRequest(req);
  const sat_audits = await getAuditsBySeverityOfHarm(severity, filter);
  res.status(200).json({ success: true, data: sat_audits });
});

exports.getAuditsByLikelihoodOfHarm = asyncHandler(async (req, res) => {
  const likelihood = req.query.likelihood || null;
  const filter = getLocationFilterFromRequest(req);
  const sat_audits = await getAuditsByLikelihoodOfHarm(likelihood, filter);
  res.status(200).json({ success: true, data: sat_audits });
});
