import backupService from '../services/backupService.js';
import logAudit from '../utils/audit.js';

export const downloadBackup = async (req, res, next) => {
  try {
    const backup = await backupService.createBackup(req);
    const stamp = new Date().toISOString().slice(0, 10);
    const filename = `storepro-backup-${stamp}.json`;
    const payload = JSON.stringify(backup);
    // Record file size for backup history (audit trail is the history source)
    logAudit(req, 'BACKUP_FILE_GENERATED', 'backup', '', {
      filename,
      fileSize: Buffer.byteLength(payload, 'utf8'),
      counts: backup.meta?.counts || {},
      version: backup.meta?.version,
    });
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Content-Disposition', `attachment; filename=${filename}`);
    res.send(payload);
  } catch (error) {
    next(error);
  }
};

export const restore = async (req, res, next) => {
  try {
    if (req.body?.confirm !== true) {
      return res.status(400).json({
        success: false,
        message: 'Restore requires explicit confirmation (confirm: true)',
      });
    }
    const result = await backupService.restoreBackup(req.body.backup, req);
    res.json({ success: true, message: 'Backup restored successfully', data: result });
  } catch (error) {
    next(error);
  }
};

export const inspect = async (req, res, next) => {
  try {
    const { meta, counts } = backupService.validateBackupPayload(req.body?.backup || req.body);
    res.json({ success: true, data: { meta, counts } });
  } catch (error) {
    next(error);
  }
};
