package com.mvrent.carrental.controller;

import com.mvrent.carrental.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/** Admin profile page + AJAX password change. */
@Controller
@RequiredArgsConstructor
public class AdminProfileController {

    private final UserService userService;

    @GetMapping("/admin/profile")
    public String profile(@AuthenticationPrincipal UserDetails principal, Model model) {
        model.addAttribute("user", userService.findByUsername(principal.getUsername()));
        return "admin/profile";
    }

    @PostMapping("/admin/api/profile/password")
    @ResponseBody
    public ResponseEntity<?> changePassword(@AuthenticationPrincipal UserDetails principal,
                                            @RequestBody Map<String, String> body) {
        try {
            userService.changePassword(principal.getUsername(),
                    body.get("currentPassword"), body.get("newPassword"));
            return ResponseEntity.ok(Map.of("ok", true));
        } catch (IllegalArgumentException ex) {
            return ResponseEntity.badRequest().body(Map.of("ok", false, "message", ex.getMessage()));
        }
    }
}
