package com.zioinfo.kintex.work.notification;

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 org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/** 알림 API (/api/work/notifications). 인증 사용자(본인 알림). */
@RestController
@RequestMapping("/api/work/notifications")
public class NotificationController {

    private final NotificationService service;
    private final EventAccessGuard guard;

    public NotificationController(NotificationService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<PageResponse<NotificationDto>> list(
            @AuthenticationPrincipal KintexPrincipal principal,
            @RequestParam(defaultValue = "false") boolean unreadOnly,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        guard.require(principal);
        return ApiResponse.ok(service.list(principal, unreadOnly, 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("/{id}/read")
    public ApiResponse<Void> read(@AuthenticationPrincipal KintexPrincipal principal,
                                  @PathVariable String id) {
        guard.require(principal);
        service.markRead(principal, id);
        return ApiResponse.ok(null);
    }

    @PostMapping("/read-all")
    public ApiResponse<Void> readAll(@AuthenticationPrincipal KintexPrincipal principal) {
        guard.require(principal);
        service.markAllRead(principal);
        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);
    }
}
