package ru.soune.nocopy.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.soune.nocopy.configuration.search.SearchProperties;
import ru.soune.nocopy.dto.BaseResponse;
import ru.soune.nocopy.dto.search.config.SearchSettingsDto;

import java.util.Map;


@Slf4j
@RestController
@RequestMapping("/api/search/settings")
@RequiredArgsConstructor
public class SearchSettingsController {

    private final SearchProperties searchProperties;

    @GetMapping
    public ResponseEntity<?> getSettings() {
        SearchSettingsDto dto = new SearchSettingsDto();

        dto.setEngines(Map.of(
                "yandex", searchProperties.getEngines().get("yandex").isEnabled(),
                "google", searchProperties.getEngines().get("google").isEnabled()));

        dto.setProxyEnabled(searchProperties.getProxy().isEnabled());

        return ResponseEntity.ok().body(BaseResponse.builder()
                .messageDesc("Success")
                .messageBody(dto)
                .build());
    }

    @PutMapping
    public ResponseEntity<?> updateSettings(@RequestBody SearchSettingsDto settings) {
        if (settings.getEngines() != null) {
            settings.getEngines().forEach((key, value) -> {
                if (searchProperties.getEngines().containsKey(key)) {
                    searchProperties.getEngines().get(key).setEnabled(value);
                }
            });
        }

        if (settings.getProxyEnabled() != null) {
            searchProperties.getProxy().setEnabled(settings.getProxyEnabled());
        }

        log.info("Settings updated: {}", settings);

        return ResponseEntity.ok().body(BaseResponse.builder()
                .messageDesc("Settings updated")
                .build());
    }
}
