package com.dbnt.kcscbackend.admin.boards;

import com.dbnt.kcscbackend.admin.boards.entity.TnBbs;
import com.dbnt.kcscbackend.admin.boards.service.AdminBoardsService;
import com.dbnt.kcscbackend.admin.config.entity.TcMenu;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.config.common.BaseController;
import com.dbnt.kcscbackend.config.common.ResponseCode;
import com.dbnt.kcscbackend.config.common.ResultVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/boards")
@Tag(name = "AdminBoardsController", description = "사이트관리 게시판현황")
public class AdminBoardsController extends BaseController {

    private final AdminBoardsService adminBoardsService;

    /* ---- 게시판관리 ----- */
    @Operation(
            summary = "게시판 목록 조회",
            description = "게시판 목록 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.GET, value = "/board-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getBoardList() throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("boardList", adminBoardsService.selectBoardList());
        resultVO.setResult(resultMap);
        return resultVO;
    }

    @Operation(
            summary = "게시판 저장",
            description = "게시판 저장",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "저장 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.PUT, value = "/board-mgt")
    public ResultVO saveBoardMgt(@RequestBody @Valid TnBbs bbs, Errors errors, @AuthenticationPrincipal LoginVO user) {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            if (errors.hasErrors()) {
                StringBuilder msg = new StringBuilder();
                for (FieldError error : errors.getFieldErrors()) {
                    msg.append(error.getDefaultMessage());
                    msg.append("\n");
                }
                resultVO.setResultCode(ResponseCode.INPUT_CHECK_ERROR.getCode());
                resultVO.setResultMessage(msg.toString());
            } else {
                System.out.println("@@@ bbs.getBbsSeq() : " + bbs.getBbsSeq());
                adminBoardsService.saveBoard(bbs, user.getId());
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            }
        }
        return resultVO;
    }

    @Operation(
            summary = "게시판 삭제",
            description = "게시판 삭제",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "삭제 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.DELETE, value = "/board-mgt")
    public ResultVO removeBoardMgt(@RequestBody TnBbs bbs, @AuthenticationPrincipal LoginVO user) {
        ResultVO resultVO = new ResultVO();
        if (user == null) {
            resultVO.setResultCode(ResponseCode.TOKEN_EXPIRED.getCode());
        } else {
            String result = adminBoardsService.deleteBoard(bbs, user.getId());
            if (result == null) {
                resultVO.setResultCode(ResponseCode.SUCCESS.getCode());
            } else if (result.equals("notFind")) {
                resultVO.setResultCode(ResponseCode.SAVE_ERROR.getCode());
                resultVO.setResultMessage("대상이 존재하지 않습니다.");
            }
        }
        return resultVO;
    }

    /* ---- 게시물관리 ----- */
    @Operation(
            summary = "게시물 목록 조회",
            description = "게시물 목록 조회",
            tags = {"AdminBoardsController"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "조회 성공"),
            @ApiResponse(responseCode = "403", description = "인가된 사용자가 아님")
    })
    @RequestMapping(method = RequestMethod.GET, value = "/post-list", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResultVO getPostList() throws Exception {
        ResultVO resultVO = new ResultVO();
        Map<String, Object> resultMap = new HashMap<>();

        resultMap.put("boardList", adminBoardsService.selectBoardList());
        resultVO.setResult(resultMap);
        return resultVO;
    }
}
