package com.zioinfo.kintex.work.worklog;

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.*;

/** 업무일지 API (/api/work/worklogs). 인증 사용자. DataScope는 서비스에서 적용. */
@RestController
@RequestMapping("/api/work/worklogs")
public class WorklogController {

    private final WorklogService service;
    private final EventAccessGuard guard;

    public WorklogController(WorklogService service, EventAccessGuard guard) {
        this.service = service;
        this.guard = guard;
    }

    @GetMapping
    public ApiResponse<PageResponse<WorklogDto>> list(
            @AuthenticationPrincipal KintexPrincipal principal,
            @RequestParam(required = false) String eventId,
            @RequestParam(required = false) String fromDate,
            @RequestParam(required = false) String toDate,
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {
        guard.require(principal);
        return ApiResponse.ok(service.list(principal, eventId, fromDate, toDate, status, page, size));
    }

    @GetMapping("/{id}")
    public ApiResponse<WorklogDto> get(@AuthenticationPrincipal KintexPrincipal principal,
                                       @PathVariable String id) {
        guard.require(principal);
        return ApiResponse.ok(service.get(principal, id));
    }

    @PostMapping
    public ApiResponse<WorklogDto> create(@AuthenticationPrincipal KintexPrincipal principal,
                                          @Valid @RequestBody WorklogSaveRequest req) {
        guard.require(principal);
        return ApiResponse.ok(service.create(principal, req));
    }

    @PutMapping("/{id}")
    public ApiResponse<WorklogDto> update(@AuthenticationPrincipal KintexPrincipal principal,
                                          @PathVariable String id,
                                          @Valid @RequestBody WorklogSaveRequest req) {
        guard.require(principal);
        return ApiResponse.ok(service.update(principal, id, req));
    }

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