package com.psg.dlsysinfo.dl_sysinfo_server.controller;

import com.psg.dlsysinfo.dl_sysinfo_server.dto.DeviceDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.dto.UserDTO;
import com.psg.dlsysinfo.dl_sysinfo_server.security.CurrentUser;
import com.psg.dlsysinfo.dl_sysinfo_server.service.*;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private UserService userService;

    @Autowired
    private CachedVulnService cachedVulnService;

    @Autowired
    private CachedSoftwareService cachedSoftwareService;

    @Autowired
    private VulnerabilityScannerService scannerService;

    @Autowired
    private NormalizationService normalizationService;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private CveStatisticsService cveStatisticsService;


    @GetMapping("/devices")
    public ResponseEntity<List<DeviceDTO>> getAllDevices(@AuthenticationPrincipal CurrentUser user) {
        return ResponseEntity.ok(deviceService.getAllDevices());
    }

    @GetMapping("/devices/client/{clientId}")
    public ResponseEntity<List<DeviceDTO>> getDevicesForClient(@PathVariable Long clientId, @AuthenticationPrincipal CurrentUser user) {
        return ResponseEntity.ok(deviceService.getDevicesForClient(clientId));
    }

    @GetMapping("/users")
    public ResponseEntity<List<UserDTO>> getAllUsersDecrypted(@AuthenticationPrincipal CurrentUser user) {
        return ResponseEntity.ok(userService.getAllDecryptedUsers());
    }

    @PutMapping("/users/{userId}/enabled")
    public ResponseEntity<Void> setUserEnabled(
            @PathVariable Long userId,
            @RequestParam boolean enabled,
            @AuthenticationPrincipal CurrentUser user
    ) {
        userService.setUserEnabledState(userId, enabled);
        return ResponseEntity.ok().build();
    }

    @Transactional
    @PostMapping("/vulns/refresh-cache")
    public ResponseEntity<String> triggerVulnRefresh(@AuthenticationPrincipal CurrentUser user) {
        String summary = cachedVulnService.refreshVulnerabilityCacheWithSummary();
        return ResponseEntity.ok("✅ Scan complete:\n" + summary);
    }

    @PostMapping("/software/refresh-cache")
    public ResponseEntity<String> triggerSoftwareCacheRefresh(@AuthenticationPrincipal CurrentUser user) {
        String summary = cachedSoftwareService.refreshSoftwareCacheWithSummary();
        return ResponseEntity.ok("✅ Installed software cache refresh complete:\n" + summary);
    }

    @PostMapping("/software/normalize")
    public ResponseEntity<String> normalizeSoftwareEntries(@AuthenticationPrincipal CurrentUser user) {
        int updated = normalizationService.normalizeInstalledSoftware();
        return ResponseEntity.ok("✅ Normalized " + updated + " installed software records.");
    }

    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getCveStats() {
        try {
            Map<String, Object> stats = jdbcTemplate.queryForMap("SELECT * FROM cve_statistics ORDER BY last_updated DESC LIMIT 1");
            return ResponseEntity.ok(stats);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }
    @PostMapping("/statistics/refresh")
    public ResponseEntity<String> refreshCveStatistics() {
        try {
            cveStatisticsService.refreshStatistics();
            return ResponseEntity.ok("✅ CVE statistics refreshed successfully.");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("❌ Failed to refresh CVE statistics.");
        }
    }




}
