const express = require('express');
const router = express.Router();
const { deployCloudFunction } = require('../tools/deploy-cloudfunc-service');

// POST /api/v1/deploy-cloudfunc
// body: { uploadUrl, uploadToken, deployApi?, deployToken?, funcInvokeUrl?, pushToken?, testCid? }
router.post('/deploy-cloudfunc', async (req, res) => {
  try {
    const body = req.body || {};
    const options = {
      uploadUrl: body.uploadUrl || process.env.CLOUD_UPLOAD_URL,
      uploadToken: body.uploadToken || process.env.CLOUD_UPLOAD_TOKEN,
      uniAppId: body.uniAppId || process.env.UNI_PUSH_APPID,
      deployApi: body.deployApi || process.env.CLOUD_DEPLOY_API,
      deployToken: body.deployToken || process.env.CLOUD_DEPLOY_TOKEN,
      funcInvokeUrl: body.funcInvokeUrl || process.env.CLOUD_FUNC_URL,
      pushToken: body.pushToken || process.env.PUSH_TOKEN,
      testCid: body.testCid || process.env.TEST_DEVICE_CID,
      deployPayload: body.deployPayload || {}
    };

    if (!options.uploadUrl) return res.status(400).json({ error: 'uploadUrl required (or set CLOUD_UPLOAD_URL env)' });

    const result = await deployCloudFunction(options);
    res.json({ ok: true, result });
  } catch (e) {
    console.error('deploy endpoint error', e);
    res.status(500).json({ ok: false, error: e && e.message });
  }
});

module.exports = router;
