package com.example.kafka.controller;

import com.example.kafka.entity.User;
import com.example.kafka.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * User controller for CRUD operation of user activities
 */
@RestController
@RequestMapping("/v1/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    /**
     * Create user
     * @param user The user
     * @return The mono of User
     */
    @PostMapping("/create")
    @ResponseStatus(HttpStatus.ACCEPTED)
    public Mono<User> createUser(@RequestBody User user){
        return userService.createUser(user);
    }

    /**
     * Display all users data
     * @return The Flux of user
     */
    @GetMapping("/all")
    public Flux<User> getAllUsers(){
        return userService.getAllUsers();
    }

    /**
     * Fetch particular user by user id
     * @param userId The userId
     * @return ResponseEntity of user
     */
    @GetMapping("/{userId}")
    public Mono<ResponseEntity<User>> getUserById(@PathVariable String userId){
        Mono<User> user = userService.findById(userId);
        return user.map(ResponseEntity::ok)
                .defaultIfEmpty(ResponseEntity.notFound().build());
    }

    @GetMapping
    public Flux<User> getUserByDepartments(@RequestParam(value = "departmentName") String departmentName){
        return userService.fetchUserByDepartmentName(departmentName);
    }

    /**
     * Update the user data
     * @param userId The userId
     * @param user The user data
     * @return ResponseEntity of user
     */
    @PutMapping("/{userId}")
    public Mono<ResponseEntity<User>> updateUserById(@PathVariable String userId, @RequestBody User user){
        return userService.updateUser(userId,user)
                .map(ResponseEntity::ok)
                .defaultIfEmpty(ResponseEntity.badRequest().build());
    }

}

