package com.it.rattan.monisuo.controller;

import com.it.rattan.monisuo.common.Result;
import com.it.rattan.monisuo.entity.Coin;
import com.it.rattan.monisuo.service.CoinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 行情接口
 */
@RestController
@RequestMapping("/api/market")
public class MarketController {

    @Autowired
    private CoinService coinService;

    /**
     * 币种列表
     */
    @GetMapping("/list")
    public Result<Map<String, Object>> getCoinList() {
        try {
            List<Coin> coins = coinService.getActiveCoins();
            Map<String, Object> result = new HashMap<>();
            result.put("list", coins);
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 币种详情
     */
    @GetMapping("/detail")
    public Result<Coin> getCoinDetail(@RequestParam String code) {
        try {
            Coin coin = coinService.getCoinByCode(code);
            if (coin == null) {
                return Result.fail("币种不存在");
            }
            return Result.success(coin);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 搜索币种
     */
    @GetMapping("/search")
    public Result<Map<String, Object>> searchCoins(@RequestParam String keyword) {
        try {
            List<Coin> coins = coinService.getActiveCoins();
            List<Coin> filtered = new java.util.ArrayList<>();
            for (Coin coin : coins) {
                if (coin.getCode().toLowerCase().contains(keyword.toLowerCase()) ||
                        coin.getName().toLowerCase().contains(keyword.toLowerCase())) {
                    filtered.add(coin);
                }
            }
            Map<String, Object> result = new HashMap<>();
            result.put("list", filtered);
            return Result.success(result);
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }
}
