package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.SystemNoticeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/system-notices")
@RequiredArgsConstructor
@Slf4j
public class SystemNoticeController {

    private final SystemNoticeService systemNoticeService;

    /**
     * GET /api/system-notices
     * 공지사항 목록 조회
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getSystemNoticeList(
            @RequestAttribute("company_code") String companyCode,
            @RequestParam Map<String, Object> queryParams) {
        queryParams.put("company_code", companyCode);
        List<Map<String, Object>> list = systemNoticeService.getSystemNoticeList(queryParams);
        return ResponseEntity.ok(ApiResponse.success(list));
    }

    /**
     * POST /api/system-notices
     * 공지사항 등록
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> insertSystemNotice(
            @RequestBody Map<String, Object> body,
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId) {

        String title = (String) body.get("title");
        String content = (String) body.get("content");

        if (title == null || title.isBlank()) {
            return ResponseEntity.status(400).body(ApiResponse.error("제목을 입력해주세요."));
        }
        if (content == null || content.isBlank()) {
            return ResponseEntity.status(400).body(ApiResponse.error("내용을 입력해주세요."));
        }

        Map<String, Object> params = new HashMap<>(body);
        params.put("company_code", companyCode);
        params.put("created_by", userId);

        try {
            Map<String, Object> created = systemNoticeService.insertSystemNotice(params);
            return ResponseEntity.status(HttpStatus.CREATED)
                    .body(ApiResponse.success(created, "공지사항이 등록되었습니다."));
        } catch (Exception e) {
            log.error("공지사항 등록 실패", e);
            return ResponseEntity.status(500).body(ApiResponse.error("공지사항 등록 중 오류가 발생했습니다."));
        }
    }

    /**
     * PUT /api/system-notices/:id
     * 공지사항 수정
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateSystemNotice(
            @PathVariable Long id,
            @RequestBody Map<String, Object> body,
            @RequestAttribute("company_code") String companyCode) {

        String title = (String) body.get("title");
        String content = (String) body.get("content");

        if (title == null || title.isBlank()) {
            return ResponseEntity.status(400).body(ApiResponse.error("제목을 입력해주세요."));
        }
        if (content == null || content.isBlank()) {
            return ResponseEntity.status(400).body(ApiResponse.error("내용을 입력해주세요."));
        }

        Map<String, Object> params = new HashMap<>(body);
        params.put("id", id);
        params.put("company_code", companyCode);

        try {
            Map<String, Object> updated = systemNoticeService.updateSystemNotice(params);
            return ResponseEntity.ok(ApiResponse.success(updated, "공지사항이 수정되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("공지사항 수정 실패: id={}", id, e);
            return ResponseEntity.status(500).body(ApiResponse.error("공지사항 수정 중 오류가 발생했습니다."));
        }
    }

    /**
     * DELETE /api/system-notices/:id
     * 공지사항 삭제
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteSystemNotice(
            @PathVariable Long id,
            @RequestAttribute("company_code") String companyCode) {

        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("company_code", companyCode);

        try {
            systemNoticeService.deleteSystemNotice(params);
            return ResponseEntity.ok(ApiResponse.success(null, "공지사항이 삭제되었습니다."));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(404).body(ApiResponse.error(e.getMessage()));
        } catch (Exception e) {
            log.error("공지사항 삭제 실패: id={}", id, e);
            return ResponseEntity.status(500).body(ApiResponse.error("공지사항 삭제 중 오류가 발생했습니다."));
        }
    }
}
