package com.mvrent.carrental.controller;

import com.mvrent.carrental.service.UserService;
import com.mvrent.carrental.web.StaffDto;
import com.mvrent.carrental.web.StaffForm;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** JSON API backing the staff / user management screen. */
@RestController
@RequestMapping("/admin/api/users")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGE_USERS')")
public class AdminUserApiController {

    private final UserService userService;

    @GetMapping
    public List<StaffDto> list() {
        return userService.findStaff().stream().map(StaffDto::from).toList();
    }

    @GetMapping("/{id}")
    public StaffDto get(@PathVariable Long id) {
        return StaffDto.from(userService.findById(id));
    }

    @PostMapping
    public ResponseEntity<?> save(@RequestBody StaffForm f) {
        try {
            var saved = (f.id() != null) ? userService.updateStaff(f) : userService.createStaff(f);
            return ResponseEntity.ok(Map.of("ok", true, "id", saved.getId()));
        } catch (IllegalArgumentException ex) {
            return bad(ex.getMessage());
        }
    }

    @PostMapping("/{id}/enabled")
    public ResponseEntity<?> setEnabled(@PathVariable Long id, @RequestParam boolean enabled) {
        try {
            userService.setEnabled(id, enabled);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (IllegalArgumentException ex) {
            return bad(ex.getMessage());
        }
    }

    @PostMapping("/{id}/password")
    public ResponseEntity<?> resetPassword(@PathVariable Long id, @RequestParam String password) {
        try {
            userService.resetPassword(id, password);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (IllegalArgumentException ex) {
            return bad(ex.getMessage());
        }
    }

    @PostMapping("/{id}/delete")
    public ResponseEntity<?> delete(@PathVariable Long id) {
        try {
            userService.deleteStaff(id);
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (IllegalArgumentException ex) {
            return bad(ex.getMessage());
        }
    }

    private static ResponseEntity<Map<String, Object>> bad(String m) {
        return ResponseEntity.badRequest().body(Map.of("ok", false, "message", m == null ? "Operation failed" : m));
    }
}
