/*
 * Copyright (c) 2024 LangChat. TyCoding All Rights Reserved.
 *
 * Licensed under the GNU Affero General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.gnu.org/licenses/agpl-3.0.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.iocoder.yudao.module.langchat.controller.admin.aigc;


import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.langchat.component.EmbeddingRefreshEvent;
import cn.iocoder.yudao.module.langchat.entity.AigcEmbedStore;
import cn.iocoder.yudao.module.langchat.service.aigc.AigcEmbedStoreService;
import cn.iocoder.yudao.module.langchat.annotation.ApiLog;
import cn.iocoder.yudao.module.langchat.component.SpringContextHolder;
import cn.iocoder.yudao.module.langchat.utils.MybatisUtil;
import cn.iocoder.yudao.module.langchat.utils.QueryPage;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author tycoding
 * @since 2024/4/15
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/chat/aigc/embed-store")
public class AigcEmbedStoreController {

    private final AigcEmbedStoreService embedStoreService;
    private final SpringContextHolder contextHolder;

    @GetMapping("/list")
    @TenantIgnore
    public CommonResult<List<AigcEmbedStore>> list(AigcEmbedStore data) {
        List<AigcEmbedStore> list = embedStoreService.list(Wrappers.lambdaQuery());
        list.forEach(this::hide);
        return CommonResult.success(list);
    }

    @GetMapping("/page")
    @TenantIgnore
    public CommonResult<Dict> page(AigcEmbedStore embedStore, QueryPage queryPage) {
        IPage<AigcEmbedStore> page = embedStoreService.page(MybatisUtil.wrap(embedStore, queryPage),
                Wrappers.lambdaQuery());
        page.getRecords().forEach(this::hide);
        return CommonResult.success(MybatisUtil.getData(page));
    }

    @GetMapping("/{id}")
    @TenantIgnore
    public CommonResult<AigcEmbedStore> findById(@PathVariable String id) {
        AigcEmbedStore store = embedStoreService.getById(id);
        hide(store);
        return CommonResult.success(store);
    }

    @PostMapping
    @ApiLog("新增向量库")
    @TenantIgnore
    @PreAuthorize("@ss.hasPermission('aigc:embed-store:add')")
    public CommonResult<AigcEmbedStore> add(@RequestBody AigcEmbedStore data) {
        if (StrUtil.isNotBlank(data.getPassword()) && data.getPassword().contains("*")) {
            data.setPassword(null);
        }
        embedStoreService.save(data);
        SpringContextHolder.publishEvent(new EmbeddingRefreshEvent(data));
        return CommonResult.success(data);
    }

    @PutMapping
    @ApiLog("修改向量库")
    @TenantIgnore
    @PreAuthorize("@ss.hasPermission('aigc:embed-store:update')")
    public CommonResult update(@RequestBody AigcEmbedStore data) {
        if (StrUtil.isNotBlank(data.getPassword()) && data.getPassword().contains("*")) {
            data.setPassword(null);
        }
        embedStoreService.updateById(data);
        SpringContextHolder.publishEvent(new EmbeddingRefreshEvent(data));
        return CommonResult.success("success");
    }

    @DeleteMapping("/{id}")
    @ApiLog("删除向量库")
    @TenantIgnore
    @PreAuthorize("@ss.hasPermission('aigc:embed-store:delete')")
    public CommonResult delete(@PathVariable String id) {
        AigcEmbedStore store = embedStoreService.getById(id);
        if (store != null) {
            embedStoreService.removeById(id);
            contextHolder.unregisterBean(id);
        }
        return CommonResult.success("success");
    }

    private void hide(AigcEmbedStore data) {
        if (data == null || StrUtil.isBlank(data.getPassword())) {
            return;
        }
        String key = StrUtil.hide(data.getPassword(), 0, data.getPassword().length());
        data.setPassword(key);
    }
}
