package kr.co.accura.wtm.api;

import kr.co.accura.wtm.domain.project.dto.*;
import kr.co.accura.wtm.domain.project.service.ProjectService;
import kr.co.accura.wtm.domain.user.dto.UserDto;
import kr.co.accura.wtm.domain.user.entity.User;
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 jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wtm/projects/{projectId}/assignments")
@RequiredArgsConstructor
public class ResourceAssignController {

    private final ProjectService projectService;

    @GetMapping
    public ResponseEntity<List<ProjectAssignmentDto>> list(@PathVariable Long projectId) {
        return ResponseEntity.ok(projectService.getAssignments(projectId));
    }

    @PostMapping
    public ResponseEntity<ProjectAssignmentDto> create(@PathVariable Long projectId,
                                                       @RequestBody @Valid AssignmentCreateRequest request) {
        return ResponseEntity.ok(projectService.createAssignment(projectId, request));
    }

    @PutMapping("/{assignId}")
    public ResponseEntity<ProjectAssignmentDto> update(@PathVariable Long projectId,
                                                       @PathVariable Long assignId,
                                                       @RequestBody @Valid AssignmentCreateRequest request) {
        return ResponseEntity.ok(projectService.updateAssignment(projectId, assignId, request));
    }

    @DeleteMapping("/{assignId}")
    public ResponseEntity<Void> delete(@PathVariable Long projectId,
                                       @PathVariable Long assignId) {
        projectService.deleteAssignment(projectId, assignId);
        return ResponseEntity.noContent().build();
    }

    @GetMapping("/available")
    public ResponseEntity<Map<String, Object>> getAvailable(@PathVariable Long projectId,
                                                            Pageable pageable) {
        Page<User> page = projectService.getAvailableUsers(projectId, pageable);
        List<UserDto> users = page.getContent().stream().map(UserDto::from).toList();
        return ResponseEntity.ok(Map.of(
                "items", users,
                "total", page.getTotalElements()
        ));
    }
}
