package tech.easyflow.usercenter.controller.ai;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.http.HttpUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.ai.entity.Resource;
import tech.easyflow.ai.service.ResourceService;
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.system.entity.vo.RoleCategoryAccessSnapshot;
import tech.easyflow.system.service.CategoryPermissionService;

import java.io.ByteArrayInputStream;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import static tech.easyflow.ai.entity.table.ResourceTableDef.RESOURCE;

/**
 * 素材库
 *
 * @author ArkLight
 * @since 2025-06-27
 */
@RestController
@RequestMapping("/userCenter/resource")
@UsePermission(moduleName = "/api/v1/resource")
public class UcResourceController extends BaseCurdController<ResourceService, Resource> {
    @javax.annotation.Resource
    private CategoryPermissionService categoryPermissionService;

    public UcResourceController(ResourceService service) {
        super(service);
    }

    @Override
    protected Result<?> onSaveOrUpdateBefore(Resource entity, boolean isSave) {
        LoginAccount loginUser = SaTokenUtil.getLoginAccount();
        if (isSave) {
            String resourceUrl = entity.getResourceUrl();
            byte[] bytes = HttpUtil.downloadBytes(resourceUrl);
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            String suffix = FileTypeUtil.getType(stream, resourceUrl);
            entity.setSuffix(suffix);
            entity.setFileSize(BigInteger.valueOf(bytes.length));
            commonFiled(entity,loginUser.getId(),loginUser.getTenantId(), loginUser.getDeptId());
        } else {
            entity.setModified(new Date());
            entity.setModifiedBy(loginUser.getId());
        }
        return super.onSaveOrUpdateBefore(entity, isSave);
    }

    @Override
    protected Page<Resource> queryPage(Page<Resource> page, QueryWrapper queryWrapper) {
        applyCategoryPermission(queryWrapper);
        return super.queryPage(page, queryWrapper);
    }

    @Override
    public Result<List<Resource>> list(Resource entity, Boolean asTree, String sortKey, String sortType) {
        QueryWrapper queryWrapper = QueryWrapper.create(entity, buildOperators(entity));
        applyCategoryPermission(queryWrapper);
        queryWrapper.orderBy(buildOrderBy(sortKey, sortType, getDefaultOrderBy()));
        return Result.ok(service.list(queryWrapper));
    }

    @Override
    public Result<Resource> detail(String id) {
        Resource resource = service.getById(id);
        if (resource != null) {
            categoryPermissionService.assertCategoryResourceVisible("RESOURCE", resource.getCreatedBy(), resource.getCategoryId(), "无权限访问素材");
        }
        return Result.ok(resource);
    }

    private void applyCategoryPermission(QueryWrapper queryWrapper) {
        RoleCategoryAccessSnapshot access = categoryPermissionService.getCurrentAccess("RESOURCE");
        if (!access.isRestricted()) {
            return;
        }
        if (access.getCategoryIds().isEmpty()) {
            queryWrapper.eq(Resource::getCreatedBy, access.getAccountId());
            return;
        }
        queryWrapper.and(RESOURCE.CREATED_BY.eq(access.getAccountId()).or(RESOURCE.CATEGORY_ID.in(access.getCategoryIds())));
    }
}
