package com.rit.ems.controller;

import com.rit.ems.model.Setting;
import com.rit.ems.repository.SettingRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/settings")
public class SettingController {

    @Autowired
    private SettingRepository settingRepository;

    @GetMapping
    public Map<String, Object> getSettings() {
        List<Setting> list = settingRepository.findAll();
        Map<String, Object> settings = new HashMap<>();
        for (Setting s : list) {
            settings.put(s.getId(), s.getValue());
        }
        return settings;
    }

    @PostMapping
    public ResponseEntity<?> saveSetting(@RequestBody Map<String, Object> payload) {
        String key = (String) payload.get("key");
        Object value = payload.get("value");
        if (key != null) {
            Setting setting = new Setting(key, value);
            settingRepository.save(setting);
        }
        return ResponseEntity.ok(Map.of("message", "Settings saved successfully"));
    }
}
