package com.ffii.fpsms.modules.settings.web;

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.ffii.core.exception.BadRequestException;
import com.ffii.core.exception.NotFoundException;
import com.ffii.fpsms.modules.settings.entity.Settings;
import com.ffii.fpsms.modules.settings.service.SettingsService;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

@RestController
@RequestMapping("/settings")
public class SettingsController{

  private SettingsService settingsService;

  public SettingsController(SettingsService settingsService) {
    this.settingsService = settingsService;
  }

  // @Operation(summary = "list system settings")
  @GetMapping
  // @PreAuthorize("hasAuthority('ADMIN')")
  public List<Settings> listAll() {
    return this.settingsService.listAll();
  }

  // @Operation(summary = "update system setting")
  @PatchMapping("/{name}")
  // @PreAuthorize("hasAuthority('ADMIN')")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void update(@PathVariable String name, @RequestBody @Valid UpdateReq body) {
    Settings entity = this.settingsService.findByName(name)
        .orElseThrow(NotFoundException::new);
    if (!this.settingsService.validateType(entity.getType(), body.value)) {
      throw new BadRequestException();
    }

    entity.setValue(body.value);
    this.settingsService.save(entity);
  }

  public static class UpdateReq {
    @NotBlank
    private String value;

    public String getValue() {
      return value;
    }

    public void setValue(String value) {
      this.value = value;
    }
  }
}
