package cloud.nstart.terravault.ordinis.readapi.web;

import cloud.nstart.terravault.ordinis.auth.ScopeContext;
import cloud.nstart.terravault.ordinis.domain.DataScope;
import cloud.nstart.terravault.ordinis.domain.definition.DictionaryDefinition;
import cloud.nstart.terravault.ordinis.domain.definition.DictionaryDefinitionRepository;
import cloud.nstart.terravault.ordinis.readapi.dto.DictionaryListItem;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * GET /api/v1/dictionaries — список доступных справочников. Фильтрация по
 * scope такая же, как для records: возвращаются только справочники со scope ⊆
 * текущим разрешённым scope клиенту.
 */
@RestController
@RequestMapping("/api/v1/dictionaries")
public class DictionaryListController {

  private final DictionaryDefinitionRepository repository;
  private final ScopeContext scopeContext;

  public DictionaryListController(
      DictionaryDefinitionRepository repository, ScopeContext scopeContext) {
    this.repository = repository;
    this.scopeContext = scopeContext;
  }

  @GetMapping
  public List<DictionaryListItem> list(
      @RequestParam(value = "as_scope", required = false) String asScope) {

    Set<DataScope> scopes = scopeContext.resolveForRead(asScope);
    return repository.findAll().stream()
        .filter(d -> scopes.contains(d.getScope()))
        .map(DictionaryListController::toItem)
        .toList();
  }

  private static DictionaryListItem toItem(DictionaryDefinition d) {
    return new DictionaryListItem(
        d.getId(),
        d.getName(),
        d.getDisplayName(),
        d.getDescription(),
        d.getScope(),
        d.getSchemaVersion(),
        d.getBundle(),
        d.getSupportedLocales() == null ? List.of() : List.of(d.getSupportedLocales()),
        d.getDefaultLocale(),
        d.getCreatedAt(),
        d.getUpdatedAt());
  }
}
