package com.arms.api.bbs.controller;

import com.arms.api.bbs.model.enums.PostType;
import com.arms.api.bbs.model.dto.BbsDTO;
import com.arms.api.bbs.model.dto.CaptchaRequest;
import com.arms.api.bbs.model.entity.BbsEntity;
import com.arms.api.bbs.model.vo.BbsVO;
import com.arms.api.bbs.model.vo.SearchBbsVO;
import com.arms.api.bbs.service.BbsService;
import com.arms.api.util.response.CommonResponse;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import feign.Param;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/non-member/bbs")
@Slf4j
@AllArgsConstructor
public class BbsController {

    private final BbsService bbsService;

    private final DefaultKaptcha captchaProducer;

    @GetMapping("/verify/image")
    public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String captchaText = captchaProducer.createText();

        request.getSession().setAttribute("captchaText", captchaText);

        BufferedImage image = captchaProducer.createImage(captchaText);

        response.setContentType("image/jpeg");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @PostMapping("/verify/captcha")
    public ResponseEntity<String> verifyCaptcha(@RequestBody CaptchaRequest captchaRequest, HttpServletRequest request) {
        String sessionCaptcha = (String) request.getSession().getAttribute("captchaText");

        log.info("sessionCaptcha : {}", sessionCaptcha);
        log.info("captchaRequest.getCaptcha() : {}", captchaRequest.getCaptcha());

        if (captchaRequest.getCaptcha() == null) {
            return ResponseEntity.badRequest().body("캡차 입력값이 없습니다.");
        }

        if (sessionCaptcha == null) {
            return ResponseEntity.badRequest().body("캡차가 만료되었습니다.");
        }

        if (sessionCaptcha.equals(captchaRequest.getCaptcha())) {
            request.getSession().removeAttribute("captchaText");
            return ResponseEntity.ok().body("캡차 검증 성공");
        } else {
            return ResponseEntity.badRequest().body("캡차 검증 실패");
        }
    }

    @GetMapping("/board-list/only-post-list")
    public ResponseEntity<CommonResponse.ApiResult<BbsVO>> postList(@Param("baseDTO") BbsDTO bbsDTO) {
        log.info("BbsController :: postList");
        bbsDTO.setPostType(PostType.POST);
        return ResponseEntity.ok(CommonResponse.success(bbsService.bbsList(bbsDTO)));
    }

    @GetMapping("/board-list/search-bbs")
    public ResponseEntity<CommonResponse.ApiResult<BbsVO>> searchBbs(@Param("baseDTO") BbsDTO bbsDTO) {
        log.info("BbsController :: searchBbs");
        bbsDTO.setPostType(PostType.POST);
        return ResponseEntity.ok(CommonResponse.success(bbsService.searchBbs(bbsDTO)));
    }

    @PostMapping("/board-list/sort-bbs")
    public ResponseEntity<CommonResponse.ApiResult<BbsVO>> sortBbs(@RequestBody SearchBbsVO searchBbsVO) {
        log.info("BbsController :: sortBbs");
        searchBbsVO.getBbsDTO().setPostType(PostType.POST);
        return ResponseEntity.ok(CommonResponse.success(bbsService.sortBbs(
                searchBbsVO.getBbsDTO(),
                searchBbsVO.getField(),
                searchBbsVO.getValue()
        )));
    }

    @GetMapping("/board-list")
    public ResponseEntity<CommonResponse.ApiResult<BbsVO>> boardList(@Param("baseDTO") BbsDTO bbsDTO) {
        log.info("BbsController :: boardList");
        return ResponseEntity.ok(CommonResponse.success(bbsService.bbsList(bbsDTO)));
    }

    @PostMapping("/post-message")
    public ResponseEntity<CommonResponse.ApiResult<String>> savePostMessage(@RequestBody BbsDTO bbsDTO) {
        log.info("BbsController :: savePostMessage");
        bbsDTO.setPostType(PostType.POST);
        return ResponseEntity.ok(CommonResponse.success(bbsService.postMessage(bbsDTO)));
    }

    @PostMapping("/reply-message")
    public ResponseEntity<CommonResponse.ApiResult<String>> saveReplyMessage(@RequestBody BbsDTO bbsDTO) {
        log.info("BbsController :: saveReplyMessage");
        if(ObjectUtils.isEmpty(bbsDTO.getPath())){
            throw new IllegalArgumentException("잘못된 요청 입니다.");
        }
        bbsDTO.setPostType(PostType.REPLY);
        return ResponseEntity.ok(CommonResponse.success(bbsService.replyMessage(bbsDTO)));
    }

    @PostMapping("check-password")
    public ResponseEntity<CommonResponse.ApiResult<String>> checkPassword(@RequestBody BbsDTO bbsDTO) {
        log.info("BbsController :: checkPassword");
        return ResponseEntity.ok(CommonResponse.success(bbsService.checkPassword(bbsDTO)));
    }

    @PutMapping("/update-id/{updateId}")
    public ResponseEntity<CommonResponse.ApiResult<String>> update(
            @PathVariable(name = "updateId") String updateId,
            @RequestBody BbsDTO bbsDTO
        ) {
        log.info("BbsController :: update");
        bbsDTO.setId(updateId);
        return ResponseEntity.ok(CommonResponse.success(bbsService.updateBbsAndGetId(bbsDTO)));
    }

    @GetMapping("/find-path/find-id/{findId}")
    public ResponseEntity<CommonResponse.ApiResult<List<BbsEntity>>> findPath(
            @PathVariable(name = "findId") String findId
    ) {
        log.info("BbsController :: findPath");
        bbsService.asyncViewCountUp(findId);
        return ResponseEntity.ok(CommonResponse.success(bbsService.findPathById(findId)));
    }

    @DeleteMapping("/delete-id/{deleteId}")
    public ResponseEntity<CommonResponse.ApiResult<String>> deleteById(
        @PathVariable(name = "deleteId") String deleteId
    ) {
        log.info("BbsController :: deleteById");
        return ResponseEntity.ok(CommonResponse.success(bbsService.deleteBbsAndGetId(deleteId)));
    }


}
