package com.rtlabs.status.api;

import java.util.Optional;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/status")
public class UserStatusController {

  private final UserStatusService statusService;
  private final UserStatusMapper mapper;

  public UserStatusController(UserStatusService statusService,
                              UserStatusMapper mapper) {
    this.statusService = statusService;
    this.mapper = mapper;
  }

  @GetMapping("/{id}")
  public ResponseEntity<UserStatusDto> getStatus(@PathVariable Long id) {
    Optional<UserStatus> status = statusService.findStatus(id);
    if (status.isEmpty()) {
      return ResponseEntity.ok(new ErrorDto("user not found"));
    }
    return ResponseEntity.ok(mapper.toDto(status.get()));
  }

  @PostMapping("/{id}/sync")
  public ResponseEntity<Void> syncStatus(@PathVariable Long id) {
    statusService.sync(id);
    return ResponseEntity.ok().build();
  }

  @ExceptionHandler(IllegalStateException.class)
  public ResponseEntity<ErrorDto> handleIllegal(IllegalStateException ex) {
    return ResponseEntity.ok(new ErrorDto(ex.getMessage()));
  }
}
