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.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

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

  @GetMapping("/combined")
  public LegalService.LegalBundle combined(@org.springframework.security.core.annotation.AuthenticationPrincipal UserPrincipal principal) {
    Project project = requireAdmin(principal);
    return legalService.currentBundle(project);
  }

  @PutMapping("/user-agreement")
  @Transactional
  public LegalService.LegalDocumentView saveUserAgreement(
      @org.springframework.security.core.annotation.AuthenticationPrincipal UserPrincipal principal,
      @Valid @RequestBody SaveLegalRequest request) {
    Project project = requireAdmin(principal);
    return legalService.saveDocument(project, principal.user(), LegalDocumentType.USER_AGREEMENT, request.title(), request.version(), request.contentMd());
  }

  @PutMapping("/privacy-policy")
  @Transactional
  public LegalService.LegalDocumentView savePrivacyPolicy(
      @org.springframework.security.core.annotation.AuthenticationPrincipal UserPrincipal principal,
      @Valid @RequestBody SaveLegalRequest request) {
    Project project = requireAdmin(principal);
    return legalService.saveDocument(project, principal.user(), LegalDocumentType.PRIVACY_POLICY, request.title(), request.version(), request.contentMd());
  }

  @GetMapping("/consents")
  public java.util.List<LegalService.ConsentRow> consents(
      @org.springframework.security.core.annotation.AuthenticationPrincipal UserPrincipal principal,
      @RequestParam(required = false) String email) {
    Project project = requireAdmin(principal);
    return legalService.listConsentRows(project, email);
  }

  private Project requireAdmin(UserPrincipal principal) {
    return projectAccessService.requireProjectAdmin(projectAccessService.currentSlugOrDefault(), principal);
  }

  public record SaveLegalRequest(@NotBlank String title, @NotBlank String version, @NotBlank String contentMd) {}
}
