package com.cloudhandson.vpdbackoffice.web;

import com.cloudhandson.vpdbackoffice.service.AppException;
import com.cloudhandson.vpdbackoffice.service.StructuredDataService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class StructuredDataController {

  private final StructuredDataService structuredDataService;

  public StructuredDataController(StructuredDataService structuredDataService) {
    this.structuredDataService = structuredDataService;
  }

  @GetMapping("/structured-data")
  public String structuredData(
      @RequestParam(required = false) String table,
      Model model
  ) {
    String selectedKey = table == null || table.isBlank() ? structuredDataService.defaultKey() : table;
    model.addAttribute("tables", structuredDataService.tables());
    model.addAttribute("selectedKey", selectedKey);
    try {
      model.addAttribute("preview", structuredDataService.preview(selectedKey));
    } catch (AppException exception) {
      model.addAttribute("errorMessage", exception.getMessage());
    }
    return "structured-data";
  }
}
