/**
 * Chain138 -> Tezos USDtz route planning API
 */

import { Router, Request, Response } from 'express';
import { planRoutes, planRoutesAsync } from './route-planner.service';

const router = Router();

router.post('/chain138-to-usdtz', async (req: Request, res: Response) => {
  try {
    const body = req.body as {
      source_chain_id?: number;
      source_asset?: string;
      source_amount?: string;
      destination_tezos_address?: string;
      max_slippage_bps?: number;
      max_total_fees?: string;
      prefer_non_custodial?: boolean;
      async_quotes?: boolean;
    };
    const request = {
      source_chain_id: body.source_chain_id ?? 138,
      source_asset: body.source_asset ?? '0xf22258f57794CC8E06237084b353Ab30fFfa640b',
      source_amount: body.source_amount ?? '0',
      destination_tezos_address: body.destination_tezos_address ?? '',
      max_slippage_bps: body.max_slippage_bps,
      max_total_fees: body.max_total_fees,
      prefer_non_custodial: body.prefer_non_custodial,
    };
    const result = body.async_quotes
      ? await planRoutesAsync(request)
      : planRoutes(request);
    if (!result.valid) {
      return res.status(400).json(result);
    }
    res.status(200).json(result);
  } catch (e) {
    res.status(500).json({
      valid: false,
      error: e instanceof Error ? e.message : 'Internal error',
    });
  }
});

export default router;
