package kr.itn.itnhub.memo;

import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;
import java.util.List;

/** 기관관리 상세의 업무메모 탭이 부르는 엔드포인트. */
@RestController
public class WorkMemoController {

    private final WorkMemoService memoService;
    private final kr.itn.itnhub.config.CurrentUser currentUser;

    public WorkMemoController(WorkMemoService memoService,
                              kr.itn.itnhub.config.CurrentUser currentUser) {
        this.memoService = memoService;
        this.currentUser = currentUser;
    }

    @GetMapping("/api/orgs/{id}/memos")
    public List<WorkMemo> list(@PathVariable Long id) {
        return memoService.list(id);
    }

    /**
     * 작성자는 본문에서 받지 않고 로그인 사용자를 서버가 직접 기록한다.
     * 요구사항 [22]로 아이디가 아니라 표시 이름이 찍힌다.
     */
    @PostMapping("/api/orgs/{id}/memos")
    public WorkMemo create(@PathVariable Long id, @Valid @RequestBody MemoRequest request,
                           Principal principal) {
        return memoService.create(id, request, currentUser.displayName(principal));
    }

    @PutMapping("/api/orgs/{id}/memos/{memoId}")
    public WorkMemo update(@PathVariable Long id, @PathVariable Long memoId,
                           @Valid @RequestBody MemoRequest request) {
        return memoService.update(id, memoId, request);
    }

    @ResponseStatus(HttpStatus.NO_CONTENT)
    @DeleteMapping("/api/orgs/{id}/memos/{memoId}")
    public void delete(@PathVariable Long id, @PathVariable Long memoId) {
        memoService.delete(id, memoId);
    }
}
