package com.davos.assessment.legal;

import com.davos.assessment.auth.UserPrincipal;
import com.davos.assessment.project.Project;
import com.davos.assessment.project.ProjectAccessService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping({"/api/legal", "/api/projects/{slug}/legal"})
public class LegalController {
  private final LegalService legalService;
  private final ProjectAccessService projectAccessService;

  public LegalController(LegalService legalService, ProjectAccessService projectAccessService) {
    this.legalService = legalService;
    this.projectAccessService = projectAccessService;
  }

  @GetMapping("/versions")
  public LegalService.LegalVersions versions() {
    return legalService.versions();
  }

  @GetMapping("/combined")
  public LegalService.LegalBundle combined() {
    return legalService.currentBundle(project());
  }

  @PostMapping("/consent")
  @Transactional
  public void consent(
      @AuthenticationPrincipal UserPrincipal principal,
      @Valid @RequestBody ConsentRequest request,
      HttpServletRequest httpServletRequest) {
    legalService.record(project(), principal.user(), request.type(), request.version(), request.granted(), httpServletRequest);
  }

  public record ConsentRequest(ConsentType type, @NotBlank String version, boolean granted) {}

  private Project project() {
    return projectAccessService.findEnabledProject(projectAccessService.currentSlugOrDefault());
  }
}
