package com.seer.teach.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.admin.convert.AdminAiApiKeyConvert;
import com.seer.teach.admin.request.AdminAiApiKeyPageReq;
import com.seer.teach.admin.request.AdminAiApiKeyQueryReq;
import com.seer.teach.admin.request.AdminAiApiKeyReq;
import com.seer.teach.admin.response.AdminAiApiKeyResp;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.teacher.module.entity.AiApiKeyEntity;
import com.seer.teach.teacher.service.IAiApiKeyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminAiApiKeyService {

    private final IAiApiKeyService aiApiKeyService;

    public PageListBean<AdminAiApiKeyResp> pageList(AdminAiApiKeyPageReq pageRequest) {
        log.info("分页查询AI API密钥列表，请求参数: {}", pageRequest);
        IPage<AiApiKeyEntity> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());

        IPage<AiApiKeyEntity> result = aiApiKeyService.page(page, new LambdaQueryWrapper<AiApiKeyEntity>()
                .eq(Objects.nonNull(pageRequest.getId()), AiApiKeyEntity::getId, pageRequest.getId())
                .like(StringUtils.hasText(pageRequest.getKeyName()), AiApiKeyEntity::getKeyName, pageRequest.getKeyName())
                .eq(StringUtils.hasText(pageRequest.getPlatform()), AiApiKeyEntity::getPlatform, pageRequest.getPlatform())
                .eq(Objects.nonNull(pageRequest.getStatus()), AiApiKeyEntity::getStatus, pageRequest.getStatus())
                .eq(Objects.nonNull(pageRequest.getExpireTime()), AiApiKeyEntity::getExpireTime, pageRequest.getExpireTime())
                .eq(Objects.nonNull(pageRequest.getIsDefault()), AiApiKeyEntity::getIsDefault, pageRequest.getIsDefault())
                .eq(Objects.nonNull(pageRequest.getOwnerId()), AiApiKeyEntity::getOwnerId, pageRequest.getOwnerId())
        );
        
        log.info("分页查询AI API密钥列表完成，查询到 {} 条记录", result.getRecords().size());
        return PageConverterUtils.convertPageListBean(result, AdminAiApiKeyConvert.INSTANCE::entityListToResponseList);
    }

    public List<AdminAiApiKeyResp> list(AdminAiApiKeyQueryReq queryParam) {
        log.info("查询AI API密钥列表，请求参数: {}", queryParam);
        List<AiApiKeyEntity> result = aiApiKeyService.list(new LambdaQueryWrapper<AiApiKeyEntity>()
                .like(StringUtils.hasText(queryParam.getKeyName()), AiApiKeyEntity::getKeyName, queryParam.getKeyName())
                .eq(Objects.nonNull(queryParam.getStatus()), AiApiKeyEntity::getStatus, queryParam.getStatus())
                .eq(Objects.nonNull(queryParam.getIsDefault()), AiApiKeyEntity::getIsDefault, queryParam.getIsDefault())
                .eq(Objects.nonNull(queryParam.getOwnerId()), AiApiKeyEntity::getOwnerId, queryParam.getOwnerId())
        );
        log.info("查询AI API密钥列表完成，查询到 {} 条记录", result.size());
        return AdminAiApiKeyConvert.INSTANCE.entityListToResponseList(result);
    }

    public AdminAiApiKeyResp getDetail(Integer id) {
        log.info("根据ID获取AI API密钥详情，ID: {}", id);
        AiApiKeyEntity result = aiApiKeyService.getById(id);
        log.info("获取AI API密钥详情完成，ID: {}，结果: {}", id, result);
        return AdminAiApiKeyConvert.INSTANCE.entityToResponse(result);
    }

    public boolean save(AdminAiApiKeyReq aiApiKey) {
        log.info("保存AI API密钥，请求参数: {}", aiApiKey);
        AiApiKeyEntity entity = AdminAiApiKeyConvert.INSTANCE.reqToEntity(aiApiKey);
        
        // 校验同一用户同一平台下API密钥的唯一性
        if (entity.getOwnerId() != null && StringUtils.hasText(entity.getPlatform())) {
            long count = aiApiKeyService.count(new LambdaQueryWrapper<AiApiKeyEntity>()
                    .eq(AiApiKeyEntity::getOwnerId, entity.getOwnerId())
                    .eq(AiApiKeyEntity::getPlatform, entity.getPlatform()));
            AssertUtils.isTrue(count == 0, ResultCodeEnum.API_KEY_PLATFORM_OWNER_ALREADY_EXISTS);
        }
        
        boolean saved = aiApiKeyService.save(entity);
        log.info("保存AI API密钥完成，结果: {}，保存的实体ID: {}", saved, entity.getId());
        return saved;
    }

    public boolean updateById(AdminAiApiKeyReq aiApiKey) {
        log.info("根据ID更新AI API密钥，请求参数: {}", aiApiKey);
        AiApiKeyEntity entity = AdminAiApiKeyConvert.INSTANCE.reqToEntity(aiApiKey);
        boolean updated = aiApiKeyService.updateById(entity);
        log.info("根据ID更新AI API密钥完成，结果: {}，更新的实体ID: {}", updated, entity.getId());
        return updated;
    }

    public boolean deleteById(Integer id) {
        log.info("根据ID删除AI API密钥，ID: {}", id);
        boolean updated = aiApiKeyService.removeById(id);
        log.info("根据ID删除AI API密钥完成，结果: {}，删除的实体ID: {}", updated, id);
        return updated;
    }

    public List<AdminAiApiKeyResp> listByOwnerId(Integer ownerId, String platform) {
        log.info("查询用户ID为 {} 的API密钥列表，平台: {}", ownerId, platform);
        List<AiApiKeyEntity> result = aiApiKeyService.list(new LambdaQueryWrapper<AiApiKeyEntity>()
                .eq(AiApiKeyEntity::getOwnerId, ownerId)
                .eq(StringUtils.hasText(platform), AiApiKeyEntity::getPlatform, platform));
        log.info("查询用户ID为 {} 的API密钥列表完成，查询到 {} 条记录", ownerId, result.size());
        return AdminAiApiKeyConvert.INSTANCE.entityListToResponseList(result);
    }
}