package tech.easyflow.usercenter.controller.ai;

import cn.hutool.core.collection.CollectionUtil;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.dao.DuplicateKeyException;
import tech.easyflow.ai.entity.Bot;
import tech.easyflow.ai.entity.BotRecentlyUsed;
import tech.easyflow.ai.service.BotRecentlyUsedService;
import tech.easyflow.ai.service.BotService;
import tech.easyflow.common.annotation.UsePermission;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.controller.BaseCurdController;
import tech.easyflow.common.web.jsonbody.JsonBody;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 最近使用 控制层。
 *
 * @author ArkLight
 * @since 2025-12-18
 */
@RestController
@RequestMapping("/userCenter/botRecentlyUsed")
@UsePermission(moduleName = "/api/v1/bot")
public class UcBotRecentlyUsedController extends BaseCurdController<BotRecentlyUsedService, BotRecentlyUsed> {

    @Resource
    private BotService botService;

    public UcBotRecentlyUsedController(BotRecentlyUsedService service) {
        super(service);
    }

    @GetMapping("/getRecentlyBot")
    public Result<List<Bot>> getRecentlyBot() {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        QueryWrapper w = QueryWrapper.create();
        w.eq(BotRecentlyUsed::getCreatedBy,account.getId());
        w.orderBy(BotRecentlyUsed::getSortNo,true);
        List<BotRecentlyUsed> list = service.list(w);
        if (CollectionUtil.isNotEmpty(list)) {
            List<BigInteger> botIds = list.stream().map(BotRecentlyUsed::getBotId).collect(Collectors.toList());
            QueryWrapper botQw = QueryWrapper.create();
            botQw.in(Bot::getId,botIds);
            List<Bot> listBot = botService.list(botQw);
            listBot.sort(Comparator.comparing(bot -> botIds.indexOf(bot.getId())));
            return Result.ok(listBot);
        }
        return Result.ok(new ArrayList<>());
    }

    @GetMapping("/removeByBotId")
    public Result<Void> removeByBotId(BigInteger botId) {
        QueryWrapper w = QueryWrapper.create();
        w.eq(BotRecentlyUsed::getBotId,botId);
        w.eq(BotRecentlyUsed::getCreatedBy,SaTokenUtil.getLoginAccount().getId());
        service.remove(w);
        return Result.ok();
    }

    @Override
    public Result<List<BotRecentlyUsed>> list(BotRecentlyUsed entity, Boolean asTree, String sortKey, String sortType) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        entity.setCreatedBy(account.getId());
        return super.list(entity, asTree, sortKey, sortType);
    }

    @Override
    protected Result<?> onSaveOrUpdateBefore(BotRecentlyUsed entity, boolean isSave) {
        entity.setCreated(new Date());
        entity.setCreatedBy(SaTokenUtil.getLoginAccount().getId());
        return super.onSaveOrUpdateBefore(entity, isSave);
    }

    @PostMapping("save")
    @Override
    public Result<?> save(@JsonBody BotRecentlyUsed entity) {
        if (entity == null || entity.getBotId() == null) {
            return Result.fail("botId不能为空");
        }
        LoginAccount account = SaTokenUtil.getLoginAccount();
        Date now = new Date();
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq(BotRecentlyUsed::getCreatedBy, account.getId())
                .eq(BotRecentlyUsed::getBotId, entity.getBotId());

        BotRecentlyUsed exist = service.getOne(queryWrapper);
        if (exist != null) {
            BotRecentlyUsed update = new BotRecentlyUsed();
            update.setId(exist.getId());
            update.setCreated(now);
            update.setSortNo(entity.getSortNo() == null ? exist.getSortNo() : entity.getSortNo());
            service.updateById(update);
            return buildSaveResult(exist.getId());
        }

        entity.setCreated(now);
        entity.setCreatedBy(account.getId());
        if (entity.getSortNo() == null) {
            entity.setSortNo(0);
        }
        try {
            service.save(entity);
            return buildSaveResult(entity.getId());
        } catch (DuplicateKeyException e) {
            BotRecentlyUsed saved = service.getOne(queryWrapper);
            if (saved != null) {
                BotRecentlyUsed update = new BotRecentlyUsed();
                update.setId(saved.getId());
                update.setCreated(now);
                service.updateById(update);
                return buildSaveResult(saved.getId());
            }
            throw e;
        }
    }

    private Result<?> buildSaveResult(BigInteger id) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("id", id);
        return Result.ok(resultMap);
    }
}
