package com.example.dateplanner.controllers.web;

import com.example.dateplanner.models.entities.AppUser;
import com.example.dateplanner.services.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.result.view.Rendering;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/account")
public class AccountController {

    private final UserService userService;

    @GetMapping("/profile")
    public Mono<Rendering> profile() {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Profile");
        model.put("index", "profile");
        return Mono.just(Rendering.view("template").model(model).build());
    }

    @PutMapping("/profile")
    @ResponseBody
    public Mono<ResponseEntity<AppUser>> updateProfile(
            @AuthenticationPrincipal AppUser currentUser,
            @RequestBody UpdateProfileRequest request) {
        if (currentUser == null) return Mono.just(ResponseEntity.status(401).build());
        currentUser.setFirstName(request.firstName());
        currentUser.setLastName(request.lastName());
        currentUser.setUpdatedAt(LocalDateTime.now());
        return userService.save(currentUser).map(ResponseEntity::ok);
    }

    public record UpdateProfileRequest(String firstName, String lastName) {}
}
