const express = require('express');
const nodeParticipantService = require('../services/nodeParticipantService');
const trxCollateralService = require('../services/trxCollateralService');
const { requireServiceAuth } = require('../middleware/serviceAuth');

const router = express.Router();

router.get('/', (req, res) => {
  res.json({
    ok: true,
    economyStats: nodeParticipantService.getEconomyStats(),
    nodes: nodeParticipantService.listNodes()
  });
});

router.get('/economy', (req, res) => {
  res.json({
    ok: true,
    stats: nodeParticipantService.getEconomyStats(),
    entries: nodeParticipantService.listEconomyEntries()
  });
});

router.get('/economy/stats', (req, res) => {
  res.json({
    ok: true,
    stats: nodeParticipantService.getEconomyStats()
  });
});

router.post('/collateral/status', requireServiceAuth, (req, res) => {
  const requestedNodeId = String(req.body?.nodeId || '').trim();
  const ownerType = requestedNodeId ? 'node' : String(req.body?.ownerType || 'aisfor_user').trim() || 'aisfor_user';
  const ownerId = requestedNodeId || String(req.body?.ownerId || req.body?.userId || '').trim();

  if (!ownerId) {
    return res.status(400).json({ ok: false, error: 'OWNER_ID_REQUIRED' });
  }

  const account = trxCollateralService.getAccount({ ownerType, ownerId });
  const config = trxCollateralService.refreshCollateralConfig();
  const minNodeCollateral = account
    ? Number(trxCollateralService.getRequiredCollateralForAccount(account) || config.minNodeCollateral || 0)
    : Number(config.minNodeCollateral || 0);
  const confirmedAmount = Number(account?.confirmedAmount || 0);
  const pendingAmount = Number(account?.pendingAmount || 0);
  const eligible = Boolean(account && account.status === 'active' && confirmedAmount >= minNodeCollateral);

  return res.json({
    ok: true,
    eligible,
    ownerType,
    ownerId,
    status: account?.status || 'waiting_deposit',
    confirmedAmount,
    pendingAmount,
    minNodeCollateral,
    asset: config.asset,
    network: config.network,
    reason: eligible ? 'collateral_confirmed' : 'collateral_required'
  });
});

router.get('/:nodeId', (req, res) => {
  const node = nodeParticipantService.getNode(req.params.nodeId);

  if (!node) {
    return res.status(404).json({ ok: false, error: 'NODE_NOT_FOUND' });
  }

  return res.json({ ok: true, node });
});

router.post('/register', requireServiceAuth, (req, res, next) => {
  try {
    const result = nodeParticipantService.registerNode(req.body || {});
    res.status(result.created ? 201 : 200).json({
      ok: true,
      created: result.created,
      serviceIdentity: req.serviceIdentity,
      node: result.node
    });
  } catch (err) {
    next(err);
  }
});

router.post('/:nodeId/heartbeat', requireServiceAuth, (req, res) => {
  const node = nodeParticipantService.heartbeat(req.params.nodeId, req.body || {});

  if (!node) {
    return res.status(404).json({ ok: false, error: 'NODE_NOT_FOUND' });
  }

  return res.json({ ok: true, node });
});

router.post('/:nodeId/status', requireServiceAuth, (req, res) => {
  const node = nodeParticipantService.updateStatus(req.params.nodeId, req.body?.status);

  if (!node) {
    return res.status(400).json({ ok: false, error: 'NODE_STATUS_UPDATE_FAILED' });
  }

  return res.json({ ok: true, node });
});

router.post('/:nodeId/pledge', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await nodeParticipantService.lockPledge(
      req.params.nodeId,
      req.body?.amount,
      req.body?.reason
    );

    if (!result) {
      return res.status(404).json({ ok: false, error: 'NODE_NOT_FOUND' });
    }

    return res.json({ ok: true, ...result });
  } catch (err) {
    next(err);
  }
});

router.post('/:nodeId/reward', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await nodeParticipantService.rewardNode(
      req.params.nodeId,
      req.body?.amount,
      req.body?.reason,
      req.body?.metadata || {}
    );

    if (!result) {
      return res.status(404).json({ ok: false, error: 'NODE_NOT_FOUND' });
    }

    return res.json({ ok: true, ...result });
  } catch (err) {
    next(err);
  }
});

router.post('/:nodeId/slash', requireServiceAuth, async (req, res, next) => {
  try {
    const result = await nodeParticipantService.slashNode(
      req.params.nodeId,
      req.body?.amount,
      req.body?.reason,
      req.body?.metadata || {}
    );

    if (!result) {
      return res.status(404).json({ ok: false, error: 'NODE_NOT_FOUND' });
    }

    return res.json({ ok: true, ...result });
  } catch (err) {
    next(err);
  }
});

module.exports = router;
