const DevManagementService = require('../../services/dev/DevManagementService');
const { logger } = require('../../middleware/logger');

function previewSql(sql, max = 180) {
  if (!sql) return '';
  const s = String(sql).replace(/\s+/g, ' ').trim();
  return s.length > max ? `${s.slice(0, max)}…` : s;
}

exports.importSqlDump = async (req, res) => {
  try {
    if (!req.file || !req.file.buffer) {
      return res.status(400).json({ success: false, error: 'SQL dump file is required' });
    }
    const sql = req.file.buffer.toString('utf8');
    if (!sql.trim()) {
      return res.status(400).json({ success: false, error: 'SQL dump file is empty' });
    }
    const start = Date.now();
    const { rows, fields } = await DevManagementService.executeDump(sql);
    const durationMs = Date.now() - start;

    const isMulti = Array.isArray(fields) && fields.length > 0 && Array.isArray(fields[0]);

    return res.json({
      success: true,
      data: { result: rows, isMulti: !!isMulti },
      meta: { durationMs }
    });
  } catch (e) {
    logger.error('[DevManagementController.importSqlDump] error', { msg: e?.message, sql: previewSql(req.file?.buffer?.toString('utf8')) });
    return res.status(500).json({ success: false, error: e?.message || 'SQL execution failed' });
  }
};

exports.listFolderStructureIssues = async (_req, res) => {
  try {
    const { list, meta } = await DevManagementService.listFolderStructureIssues();
    return res.json({ success: true, data: list, meta });
  } catch (e) {
    logger.error('[DevManagementController.listFolderStructureIssues] error', { msg: e?.message });
    return res.status(500).json({ success: false, error: e?.message || 'Failed to list folder structure issues' });
  }
};

exports.createFolderStructure = async (req, res) => {
  try {
    const userId = req.body && (req.body.userId || req.body.user_id);
    const { results, meta } = await DevManagementService.createFolderStructure({ userId });
    return res.json({ success: true, data: results, meta });
  } catch (e) {
    logger.error('[DevManagementController.createFolderStructure] error', { msg: e?.message });
    return res.status(500).json({ success: false, error: e?.message || 'Failed to create folder structure' });
  }
};

exports.listLooseFiles = async (_req, res) => {
  try {
    const { list, meta } = await DevManagementService.listLooseFiles();
    return res.json({ success: true, data: list, meta });
  } catch (e) {
    logger.error('[DevManagementController.listLooseFiles] error', { msg: e?.message });
    return res.status(500).json({ success: false, error: e?.message || 'Failed to list loose files' });
  }
};

exports.moveLooseFilesToContract = async (req, res) => {
  try {
    const userId = req.body && (req.body.userId || req.body.user_id);
    const { results, meta } = await DevManagementService.moveLooseFilesToContract({ userId });
    return res.json({ success: true, data: results, meta });
  } catch (e) {
    logger.error('[DevManagementController.moveLooseFilesToContract] error', { msg: e?.message });
    return res.status(500).json({ success: false, error: e?.message || 'Failed to move loose files' });
  }
};

exports.listGhostDirectories = async (_req, res) => {
  try {
    const { list, meta } = await DevManagementService.listGhostDirectories();
    return res.json({ success: true, data: list, meta });
  } catch (e) {
    logger.error('[DevManagementController.listGhostDirectories] error', { msg: e?.message });
    return res.status(500).json({ success: false, error: e?.message || 'Failed to list ghost directories' });
  }
};

exports.downloadStorageArchive = async (_req, res) => {
  const now = new Date();
  const pad = (value) => String(value).padStart(2, '0');
  const fileName = `exoscale-storage-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.zip`;

  try {
    res.setHeader('Content-Type', 'application/zip');
    res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);

    const meta = await DevManagementService.streamStorageArchive(res);
    logger.info('[DevManagementController.downloadStorageArchive] success', meta);
  } catch (e) {
    logger.error('[DevManagementController.downloadStorageArchive] error', { msg: e?.message });
    if (!res.headersSent) {
      return res.status(500).json({ success: false, error: e?.message || 'Failed to export Exoscale storage' });
    }
    if (!res.writableEnded) {
      res.destroy(e);
    }
  }
};
