package com.ensign.crm.module.crm.controller.crm;

import com.ensign.crm.module.crm.service.ProxyService;
import com.ensign.crm.module.system.service.permission.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;


/**
 * @Description: TODO
 * @Date: 2024/10/28 15:27
 * @Created: by ZZSLL
 */

@RestController
@RequestMapping("/crm-api")
@Slf4j
public class AuthAuthController {

    @Autowired
    private ProxyService proxyService;

    @Autowired
    private PermissionService permissionService;

    @GetMapping("/auth")
    @PermitAll
    public ResponseEntity<String> auth(HttpServletRequest request) {
        String accessToken = null;
        String userid = request.getHeader("userid");
        if (StringUtils.isBlank(userid)) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
        }
        if (!"1".equals(userid)) {
            boolean hassed = permissionService.hasAnyPermissions(Long.valueOf(userid), "crm:proxy:all");
            if (!hassed) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
        }
        try {
            accessToken = proxyService.initAccessToken();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseEntity.status(500).body(e.getMessage());
        }
        return ResponseEntity.ok(accessToken);
    }
}
