package kr.co.accura.wtm.api;

import kr.co.accura.wtm.domain.project.dto.*;
import kr.co.accura.wtm.domain.project.service.ProjectService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import kr.co.accura.wbx.spring.auth.WbxUserDetails;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wtm/projects")
@RequiredArgsConstructor
public class ProjectController {

    private final ProjectService projectService;

    @GetMapping
    public ResponseEntity<Map<String, Object>> list(Pageable pageable) {
        Page<ProjectDto> page = projectService.findAll(pageable);
        return ResponseEntity.ok(Map.of(
                "items", page.getContent(),
                "total", page.getTotalElements()
        ));
    }

    @PostMapping
    public ResponseEntity<ProjectDto> create(@RequestBody @Valid ProjectCreateRequest request) {
        return ResponseEntity.ok(projectService.create(request));
    }

    @GetMapping("/{id}")
    public ResponseEntity<ProjectDto> getById(@PathVariable Long id) {
        return ResponseEntity.ok(projectService.findById(id));
    }

    @PutMapping("/{id}")
    public ResponseEntity<ProjectDto> update(@PathVariable Long id,
                                             @RequestBody @Valid ProjectCreateRequest request) {
        return ResponseEntity.ok(projectService.update(id, request));
    }

    @GetMapping("/my")
    public ResponseEntity<List<ProjectDto>> myProjects(
            @AuthenticationPrincipal WbxUserDetails user,
            @RequestParam(required = false) Long userId) {
        Long resolvedUserId = userId != null ? userId : user.getId();
        return ResponseEntity.ok(projectService.findMyProjects(resolvedUserId));
    }

    @GetMapping("/{id}/members")
    public ResponseEntity<List<ProjectAssignmentDto>> getMembers(@PathVariable Long id) {
        return ResponseEntity.ok(projectService.getAssignments(id));
    }

    @PostMapping("/{id}/members")
    public ResponseEntity<ProjectAssignmentDto> addMember(@PathVariable Long id,
                                                          @RequestBody @Valid AssignmentCreateRequest request) {
        return ResponseEntity.ok(projectService.createAssignment(id, request));
    }
}
