package com.maternalmall.controller;

import com.maternalmall.common.ApiResponse;
import com.maternalmall.config.AuthContext;
import com.maternalmall.domain.User;
import com.maternalmall.repository.UserRepository;
import com.maternalmall.service.AuthService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    private final AuthService authService;
    private final UserRepository userRepository;

    public AuthController(AuthService authService, UserRepository userRepository) {
        this.authService = authService;
        this.userRepository = userRepository;
    }

    @PostMapping("/register")
    public ApiResponse<Map<String, Object>> register(@RequestBody Map<String, String> body) {
        return ApiResponse.ok(authService.register(body.get("username"), body.get("password"), body.getOrDefault("role", "CUSTOMER")));
    }

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@RequestBody Map<String, String> body) {
        return ApiResponse.ok(authService.login(body.get("username"), body.get("password")));
    }

    @GetMapping("/me")
    public ApiResponse<User> me(HttpServletRequest request) {
        return ApiResponse.ok(AuthContext.getUser(request));
    }

    @PutMapping("/me")
    public ApiResponse<User> updateMe(HttpServletRequest request, @RequestBody Map<String, String> body) {
        User user = AuthContext.getUser(request);
        user.setNickname(body.getOrDefault("nickname", user.getNickname()));
        user.setPhone(body.getOrDefault("phone", user.getPhone()));
        user.setAddress(body.getOrDefault("address", user.getAddress()));
        return ApiResponse.ok(userRepository.save(user));
    }
}
