package com.rj.controller;

import com.rj.dto.LbThirdIntegrationCredentialUpdateRequest;
import com.rj.entity.LbThirdIntegrationConfig;
import com.rj.service.ILbThirdIntegrationConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 租户第三方集成配置控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/lbThirdIntegrationConfig")
@Tag(name = "租户第三方集成配置", description = "lb_third_integration_config 增删改查与分页")
public class LbThirdIntegrationConfigController {

    @Autowired
    private ILbThirdIntegrationConfigService lbThirdIntegrationConfigService;

    @PostMapping("/add")
    @Operation(summary = "新增")
    public ResponseEntity<Map<String, Object>> add(
            @Parameter(description = "配置实体（凭证请传 cookie、phpsid、goodsApiToken、goodsApiAppStr 明文字段）", required = true)
            @RequestBody LbThirdIntegrationConfig entity) {
        Map<String, Object> result = lbThirdIntegrationConfigService.add(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PutMapping("/update")
    @Operation(summary = "更新")
    public ResponseEntity<Map<String, Object>> update(
            @Parameter(description = "配置实体（仅传需修改字段；凭证字段非空时才更新）", required = true)
            @RequestBody LbThirdIntegrationConfig entity) {
        Map<String, Object> result = lbThirdIntegrationConfigService.update(entity);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除")
    public ResponseEntity<Map<String, Object>> delete(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        Map<String, Object> result = lbThirdIntegrationConfigService.deleteById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/list")
    @Operation(summary = "分页查询")
    public ResponseEntity<Map<String, Object>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String tenantId,
            @RequestParam(required = false) String providerCode,
            @RequestParam(required = false) Integer enabled) {
        Map<String, Object> result = lbThirdIntegrationConfigService.pageQuery(
                current, size, tenantId, providerCode, enabled);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        return ResponseEntity.internalServerError().body(result);
    }

    @GetMapping("/get/{id}")
    @Operation(summary = "按ID查询")
    public ResponseEntity<Map<String, Object>> getById(
            @Parameter(description = "主键ID", required = true) @PathVariable String id) {
        Map<String, Object> result = lbThirdIntegrationConfigService.getDetailById(id);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if ("记录不存在".equals(result.get("message"))) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.badRequest().body(result);
    }

    @GetMapping("/credential/{tenantId}")
    @Operation(
            summary = "查询租户凭证",
            description = "按 tenantId 返回 cookie、phpsid、goodsApiToken、goodsApiAppStr 明文")
    public ResponseEntity<Map<String, Object>> getCredentialStatus(
            @Parameter(description = "租户 id", required = true) @PathVariable String tenantId) {
        Map<String, Object> result = lbThirdIntegrationConfigService.getCredentialStatusByTenantId(tenantId);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if ("该租户未配置第三方集成".equals(result.get("message"))) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.badRequest().body(result);
    }

    @PostMapping("/credential/{tenantId}")
    @Operation(
            summary = "更新租户凭证",
            description =
                    "仅更新 cookie/phpsid/goodsApiToken/goodsApiAppStr 凭证列；"
                            + "传明文则直接入库并 credential_version+1；"
                            + "传 clear* 为 true 则清除对应凭证；至少操作一项")
    public ResponseEntity<Map<String, Object>> updateCredential(
            @Parameter(description = "租户 id", required = true) @PathVariable String tenantId,
            @Parameter(description = "凭证更新请求", required = true)
                    @RequestBody
                    LbThirdIntegrationCredentialUpdateRequest request) {
        Map<String, Object> result =
                lbThirdIntegrationConfigService.updateCredentialByTenantId(tenantId, request);
        Boolean success = (Boolean) result.get("success");
        if (success != null && success) {
            return ResponseEntity.ok(result);
        }
        if ("该租户未配置第三方集成，请先新增配置".equals(result.get("message"))) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.badRequest().body(result);
    }
}
