package com.psg.dlsysinfo.dl_sysinfo_server.controller;

import com.psg.dlsysinfo.dl_sysinfo_server.dto.UserProfileDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.UserAuth;
import com.psg.dlsysinfo.dl_sysinfo_server.security.CurrentUser;
import com.psg.dlsysinfo.dl_sysinfo_server.security.EncryptionService;
import com.psg.dlsysinfo.dl_sysinfo_server.security.JwtUtil;
import com.psg.dlsysinfo.dl_sysinfo_server.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserProfileController {

    private final UserService userAuthService;
    private final EncryptionService encryptionService;
    private final JwtUtil jwtUtil;

    @PreAuthorize("isAuthenticated()")
    @GetMapping("/profile")
    public ResponseEntity<?> getUserProfile(@AuthenticationPrincipal CurrentUser user) {
        try {
            UserAuth userAuth = userAuthService.findByUsername(user.getUsername());

            UserProfileDTO profileDto = new UserProfileDTO(
                    userAuth.getUsername(),
                    encryptionService.decryptData(userAuth.getDisplayNameHash()),
                    encryptionService.decryptData(userAuth.getFirstNameHash()),
                    encryptionService.decryptData(userAuth.getLastNameHash()),
                    encryptionService.decryptData(userAuth.getEmailHash())
            );
            return ResponseEntity.ok(profileDto);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to decrypt user data");
        }
    }

    @PreAuthorize("isAuthenticated()")
    @PostMapping("/profile")
    public ResponseEntity<?> updateUserProfile(@AuthenticationPrincipal CurrentUser user,
                                               @RequestBody UserProfileDTO profileDto) {
        try {
            UserAuth userAuth = userAuthService.findByUsername(user.getUsername());

            userAuth.setDisplayNameHash(encryptionService.encryptData(profileDto.getDisplayName()));
            userAuth.setFirstNameHash(encryptionService.encryptData(profileDto.getFirstName()));
            userAuth.setLastNameHash(encryptionService.encryptData(profileDto.getLastName()));
            userAuth.setEmailHash(encryptionService.encryptData(profileDto.getEmail()));

            userAuthService.save(userAuth);

            // ✅ Rebuild token including roles
            String decryptedDisplayName = encryptionService.decryptData(userAuth.getDisplayNameHash());
            List<String> roles = List.of(userAuth.getRole());

            String newToken = jwtUtil.generateToken(
                    userAuth.getUsername(),
                    decryptedDisplayName,
                    userAuth.getClient().getClientIdentifier(),
                    userAuth.getId(),
                    roles
            );

            return ResponseEntity.ok(Map.of(
                    "message", "Profile updated successfully",
                    "token", newToken
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to encrypt or update user data");
        }
    }

}