package de.votian.services.controller;

import de.votian.services.entity.User;
import de.votian.services.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public ResponseEntity<User> findById(@PathVariable Long id) {
        return userService.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/account/{account}")
    public ResponseEntity<User> findByAccount(@PathVariable String account) {
        return userService.findByAccount(account)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping("/email/{email}")
    public ResponseEntity<List<User>> findByEmail(@PathVariable String email) {
        return ResponseEntity.ok(userService.findByEmail(email));
    }

    @GetMapping("/account-unique/{account}")
    public ResponseEntity<Boolean> isAccountUnique(@PathVariable String account,
                                                    @RequestParam(required = false) Long excludeId) {
        if (excludeId != null) {
            return ResponseEntity.ok(userService.isAccountUniqueExcluding(account, excludeId));
        }
        return ResponseEntity.ok(userService.isAccountUnique(account));
    }

    @PostMapping
    public ResponseEntity<User> save(@RequestBody User user) {
        return ResponseEntity.ok(userService.save(user));
    }

    @PutMapping("/{id}/password")
    public ResponseEntity<Void> changePassword(@PathVariable Long id, @RequestBody String passwordHash) {
        userService.changePassword(id, passwordHash);
        return ResponseEntity.ok().build();
    }

    @DeleteMapping("/{id}/password")
    public ResponseEntity<Void> clearPassword(@PathVariable Long id) {
        userService.clearPassword(id);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/{id}/totp-session")
    public ResponseEntity<Void> setTotpSessionKey(@PathVariable Long id, @RequestBody String sessionKey) {
        userService.setTotpSessionKey(id, sessionKey);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/birthdays-today")
    public ResponseEntity<List<Object[]>> getBirthdaysToday() {
        return ResponseEntity.ok(userService.getBirthdaysToday());
    }
}
