'use strict';

const express = require('express');
const { authHeaders } = require('./agentAuth');

function createInstallationWizardRouter(config) {
  const router = express.Router();

  router.get('/status', (req, res) => {
    res.json({
      ok: true,
      configured: !!(config.tenantId && config.branchId && config.agentId),
      tenant_id: config.tenantId || null,
      branch_id: config.branchId || null,
      agent_id: config.agentId || null,
    });
  });

  router.post('/proxy/:action', async (req, res) => {
    try {
      const action = req.params.action.replace(/[^a-z0-9-]/gi, '');
      const response = await fetch(`${config.cloudUrl}/api/installations/${action}`, {
        method: 'POST',
        headers: authHeaders(config),
        body: JSON.stringify(req.body || {}),
      });
      const data = await response.json();
      res.status(response.status).json(data);
    } catch (err) {
      res.status(502).json({ ok: false, error: 'Cloud no disponible', detail: err.message });
    }
  });

  return router;
}

module.exports = { createInstallationWizardRouter };
