import asyncHandler from '../utils/asyncHandler.js';
import shiftService from '../services/shiftService.js';

export const open = asyncHandler(async (req, res) => {
  const shift = await shiftService.openShift(req.body, req);
  const totals = await shiftService.computeTotals(shift);
  res.status(201).json({ success: true, message: 'Shift opened', data: { shift: { ...shift.toObject(), totals } } });
});

export const active = asyncHandler(async (req, res) => {
  const shift = await shiftService.getActiveShift(req);
  res.status(200).json({ success: true, data: { shift } });
});

export const movement = asyncHandler(async (req, res) => {
  const { movement, totals } = await shiftService.addMovement(req.params.id, req.body, req);
  res.status(201).json({
    success: true,
    message: `Cash ${movement.type === 'CASH_IN' ? 'in' : 'out'} recorded`,
    data: { movement, totals },
  });
});

export const movements = asyncHandler(async (req, res) => {
  const list = await shiftService.listMovements(req.params.id);
  res.status(200).json({ success: true, data: { movements: list } });
});

export const close = asyncHandler(async (req, res) => {
  const shift = await shiftService.closeShift(req.params.id, req.body, req);
  res.status(200).json({ success: true, message: 'Shift closed', data: { shift } });
});

export const history = asyncHandler(async (req, res) => {
  const shifts = await shiftService.listShifts(req.query);
  res.status(200).json({ success: true, data: { shifts } });
});

export const zReport = asyncHandler(async (req, res) => {
  const report = await shiftService.getZReport(req.params.id);
  res.status(200).json({ success: true, data: report });
});
