package com.css.txw.sso.controller.auth;

import cn.hutool.core.util.StrUtil;
import com.css.ggzc.framework.common.pojo.CommonResult;
import com.css.ggzc.framework.common.util.servlet.ServletUtils;
import com.css.txw.sso.constants.SsoApiConstants;
import com.css.txw.sso.constants.SsoConstants;
import com.css.txw.sso.pojo.vo.AuthLoginReqVO;
import com.css.txw.sso.service.auth.AdminAuthService;
import com.css.txw.sso.util.SecurityFrameworkUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import static com.css.ggzc.framework.common.pojo.CommonResult.success;


@Tag(name = "后台登录")
@RestController
@RequestMapping("/admin/auth")
@Validated
@Slf4j
public class AdminAuthController {

    @Resource
    private AdminAuthService adminAuthService;

    @PostMapping("/login")
    @Operation(summary = "后台登录-账号密码登录")
    public CommonResult<Boolean> login(@RequestBody @Valid AuthLoginReqVO reqVO){
        final String token = adminAuthService.login(reqVO);
        final HttpServletResponse response = ServletUtils.getResponse();
        final Cookie cookie = new Cookie(SsoConstants.ADMIN_COOKIE_TOKEN_KEY,token);
        cookie.setPath(SsoConstants.COOKIE_PATH);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);
        return success(true);
    }

    @PostMapping("/logout")
    @Operation(summary = "后台登录-退出登录")
    public CommonResult<Boolean> logout(HttpServletRequest request){
        String token = SecurityFrameworkUtils.obtainAuthorization(SsoConstants.ADMIN_COOKIE_TOKEN_KEY,request);
        if (StrUtil.isNotBlank(token)) {
            adminAuthService.logout(token);
            final HttpServletResponse response = ServletUtils.getResponse();
            final Cookie cookie = new Cookie(SsoConstants.ADMIN_COOKIE_TOKEN_KEY,token);
            cookie.setPath(SsoConstants.COOKIE_PATH);
            cookie.setHttpOnly(true);
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        return success(true);
    }

}
