package com.gxwebsoft.app.controller;

import com.gxwebsoft.app.entity.AppResource;
import com.gxwebsoft.app.param.AppResourceParam;
import com.gxwebsoft.app.service.AppResourceService;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 开发者资源管理控制器（服务器/数据库/云存储/域名/SSL）
 *
 * @author 科技小王子
 * @since 2026-03-31
 */
@Slf4j
@Tag(name = "开发者资源管理")
@RestController
@RequestMapping("/api/app/developer-resource")
public class AppResourceController extends BaseController {

    @Resource
    private AppResourceService appResourceService;

    // ─── 查询接口 ─────────────────────────────────────────────────

    @Operation(summary = "分页查询资源列表")
    @GetMapping("/page")
    public ApiResult<PageResult<AppResource>> page(AppResourceParam param) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        // 普通开发者只能查自己的资源
        param.setUserId(loginUser.getUserId());
        param.setTenantId(loginUser.getTenantId());
        return success(appResourceService.pageRel(param));
    }

    @Operation(summary = "查询资源列表（不分页）")
    @GetMapping
    public ApiResult<List<AppResource>> list(AppResourceParam param) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        param.setUserId(loginUser.getUserId());
        param.setTenantId(loginUser.getTenantId());
        return success(appResourceService.listRel(param));
    }

    @Operation(summary = "获取资源详情")
    @GetMapping("/{resourceId}")
    public ApiResult<AppResource> get(@PathVariable Long resourceId) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        AppResource resource = appResourceService.getByIdRel(resourceId);
        if (resource == null) return fail("资源不存在", null);
        if (!resource.getUserId().equals(loginUser.getUserId())) return fail("无权访问此资源", null);
        return success(resource);
    }

    @Operation(summary = "统计各类型资源数量")
    @GetMapping("/stats")
    public ApiResult<Map<String, Long>> stats() {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        return success(appResourceService.countByType(loginUser.getUserId(), loginUser.getTenantId()));
    }

    // ─── 新增/修改接口 ────────────────────────────────────────────

    @OperationLog
    @Operation(summary = "新增资源")
    @PostMapping
    public ApiResult<AppResource> save(@RequestBody AppResource resource) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        if (resource.getResourceType() == null || resource.getResourceType().isEmpty()) {
            return fail("资源类型不能为空", null);
        }
        if (resource.getName() == null || resource.getName().isEmpty()) {
            return fail("资源名称不能为空", null);
        }
        resource.setTenantId(loginUser.getTenantId());
        try {
            AppResource result = appResourceService.addResource(resource, loginUser.getUserId());
            return success("添加成功", result);
        } catch (Exception e) {
            return fail(e.getMessage(), null);
        }
    }

    @OperationLog
    @Operation(summary = "修改资源")
    @PutMapping
    public ApiResult<AppResource> update(@RequestBody AppResource resource) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录", null);
        try {
            AppResource result = appResourceService.updateResource(resource);
            return success("修改成功", result);
        } catch (Exception e) {
            return fail(e.getMessage(), null);
        }
    }

    // ─── 删除接口 ─────────────────────────────────────────────────

    @OperationLog
    @Operation(summary = "删除资源（逻辑删除）")
    @DeleteMapping("/{resourceId}")
    public ApiResult<?> remove(@PathVariable Long resourceId) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录");
        try {
            appResourceService.removeResource(resourceId, loginUser.getUserId());
            return success("删除成功");
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }

    @OperationLog
    @Operation(summary = "批量删除资源")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Long> ids) {
        User loginUser = getLoginUser();
        if (loginUser == null) return fail("请先登录");
        try {
            for (Long id : ids) {
                appResourceService.removeResource(id, loginUser.getUserId());
            }
            return success("批量删除成功");
        } catch (Exception e) {
            return fail(e.getMessage());
        }
    }
}
