package com.zioinfo.kintex.work.message;

import com.zioinfo.kintex.auth.EventAccessGuard;
import com.zioinfo.kintex.auth.KintexPrincipal;
import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.PageResponse;
import jakarta.validation.Valid;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/** 쪽지 API (/api/work/messages). 인증 사용자. */
@RestController
@RequestMapping("/api/work/messages")
public class MessageController {

    private final MessageService service;
    private final EventAccessGuard guard;

    public MessageController(MessageService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping("/inbox")
    public ApiResponse<PageResponse<MessageDto>> inbox(@AuthenticationPrincipal KintexPrincipal principal,
                                                       @RequestParam(defaultValue = "0") int page,
                                                       @RequestParam(defaultValue = "20") int size) {
        guard.require(principal);
        return ApiResponse.ok(service.inbox(principal, page, size));
    }

    @GetMapping("/sent")
    public ApiResponse<PageResponse<MessageDto>> sent(@AuthenticationPrincipal KintexPrincipal principal,
                                                      @RequestParam(defaultValue = "0") int page,
                                                      @RequestParam(defaultValue = "20") int size) {
        guard.require(principal);
        return ApiResponse.ok(service.sent(principal, page, size));
    }

    @GetMapping("/unread-count")
    public ApiResponse<Map<String, Long>> unread(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.require(principal);
        return ApiResponse.ok(Map.of("unread", service.unreadCount(principal)));
    }

    @PostMapping
    public ApiResponse<Map<String, String>> send(@AuthenticationPrincipal KintexPrincipal principal,
                                                  @Valid @RequestBody MessageSendRequest req) {
        guard.require(principal);
        return ApiResponse.ok(Map.of("id", service.send(principal, req)));
    }

    @PostMapping("/{id}/read")
    public ApiResponse<Void> read(@AuthenticationPrincipal KintexPrincipal principal,
                                  @PathVariable String id) {
        guard.require(principal);
        service.markRead(principal, id);
        return ApiResponse.ok(null);
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@AuthenticationPrincipal KintexPrincipal principal,
                                    @PathVariable String id) {
        guard.require(principal);
        service.delete(principal, id);
        return ApiResponse.ok(null);
    }
}
