package com.psg.dlsysinfo.dl_sysinfo_server.controller;

import com.psg.dlsysinfo.dl_sysinfo_server.dto.ClientDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.dto.ClientRegisterRequest;
import com.psg.dlsysinfo.dl_sysinfo_server.dto.UserRegisterRequest;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.Client;
import com.psg.dlsysinfo.dl_sysinfo_server.entity.UserAuth;
import com.psg.dlsysinfo.dl_sysinfo_server.repository.ClientRepository;
import com.psg.dlsysinfo.dl_sysinfo_server.security.EncryptionService;
import com.psg.dlsysinfo.dl_sysinfo_server.service.ClientService;
import com.psg.dlsysinfo.dl_sysinfo_server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
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;

@RestController
@RequestMapping("/api/auth")
public class RegisterController {

    @Autowired
    private ClientService clientService;

    @Autowired
    private UserService userService;

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private EncryptionService encryptionService;

    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/clients")
    public ResponseEntity<List<ClientDTO>> getAllClients() {
        List<ClientDTO> clients = clientRepository.findAll().stream()
                .map(client -> {
                    String decryptedName;
                    try {
                        decryptedName = encryptionService.decryptData(client.getClientNameEncrypted());
                    } catch (Exception e) {
                        decryptedName = "[Decryption failed]";
                    }
                    return new ClientDTO(client.getClientId(), client.getClientIdentifier(), decryptedName);
                })
                .toList();

        return ResponseEntity.ok(clients);
    }

    @PostMapping("/register/client")
    public ResponseEntity<?> registerClient(@RequestBody ClientRegisterRequest request) {
        Client client = clientService.registerClient(request.getClientName());
        return ResponseEntity.ok(Map.of(
                "clientId", client.getClientId(),
                "clientIdentifier", client.getClientIdentifier()
        ));
    }

    @PostMapping("/register/user")
    public ResponseEntity<?> registerUser(@RequestBody UserRegisterRequest request) {
        UserAuth user = userService.registerUser(
                request.getUsername(),
                request.getPassword(),
                request.getRole(),
                request.getClientId()
        );
        return ResponseEntity.ok(Map.of("userId", user.getId()));
    }
}
