import { Router, Request, Response } from 'express';
import fs from 'fs';
import path from 'path';
import { authenticate, requireRole } from '../../middleware/auth';
import { env } from '../../config/env';
import * as backupService from '../../services/backup.service';

const router = Router();

router.use(authenticate);

// ─── Cross-Instance Backup Endpoints ────────────────────────────────

// List all backups (cross-instance)
router.get('/', requireRole('SUPER_ADMIN', 'OPERATOR'), async (req: Request, res: Response) => {
  const { instanceId, page, limit } = req.query;
  const pageNum = Math.max(1, parseInt(page as string, 10) || 1);
  const limitNum = Math.min(100, Math.max(1, parseInt(limit as string, 10) || 50));

  const result = await backupService.listBackups(
    instanceId as string | undefined,
    pageNum,
    limitNum
  );
  res.json(result);
});

// Delete a backup
router.delete(
  '/:backupId',
  requireRole('SUPER_ADMIN'),
  async (req: Request, res: Response) => {
    await backupService.deleteBackup(req.params.backupId as string, req.user!.id, req.ip);
    res.json({ message: 'Backup deleted' });
  }
);

// Download a backup archive
router.get(
  '/:backupId/download',
  requireRole('SUPER_ADMIN'),
  async (req: Request, res: Response) => {
    const backup = await backupService.getBackup(req.params.backupId as string);

    if (!backup.archivePath || backup.status !== 'COMPLETED') {
      res.status(400).json({ error: { message: 'Backup not available for download', code: 'NOT_AVAILABLE' } });
      return;
    }

    // Validate path is within backup storage (prevent traversal)
    const normalized = path.resolve(backup.archivePath);
    const normalizedStorage = path.resolve(env.BACKUP_STORAGE_PATH);
    if (!normalized.startsWith(normalizedStorage + path.sep)) {
      res.status(403).json({ error: { message: 'Access denied', code: 'FORBIDDEN' } });
      return;
    }
    if (!fs.existsSync(normalized)) {
      res.status(404).json({ error: { message: 'Backup file not found', code: 'FILE_NOT_FOUND' } });
      return;
    }

    const filename = path.basename(normalized);
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.setHeader('Content-Type', 'application/gzip');

    const stream = fs.createReadStream(normalized);
    stream.pipe(res);
  }
);

export default router;
