package pl.polskalokalnie.lead;

import jakarta.validation.constraints.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import pl.polskalokalnie.user.AppUser;
import pl.polskalokalnie.user.UserRepository;

/**
 * Zgody marketingowe zalogowanego uzytkownika. Zapisywane na leadzie powiazanym z kontem, dzieki
 * czemu realnie steruja kwalifikacja uzytkownika jako odbiorcy kampanii. Endpoint wymaga
 * uwierzytelnienia (regula anyRequest().authenticated() w SecurityConfig).
 */
@RestController
@RequestMapping("/api/me/marketing")
public class MarketingConsentController {

    private final UserRepository userRepository;
    private final LeadSyncService leadSyncService;

    public MarketingConsentController(UserRepository userRepository, LeadSyncService leadSyncService) {
        this.userRepository = userRepository;
        this.leadSyncService = leadSyncService;
    }

    @GetMapping
    public MarketingConsentResponse get(Authentication authentication) {
        AppUser user = currentUser(authentication);
        Lead lead = leadSyncService.getOrCreateForUser(user);
        return MarketingConsentResponse.from(lead);
    }

    @PutMapping
    public MarketingConsentResponse update(Authentication authentication, @RequestBody MarketingConsentRequest request) {
        AppUser user = currentUser(authentication);
        Lead lead = leadSyncService.updateConsentForUser(user,
                Boolean.TRUE.equals(request.emailConsent()),
                Boolean.TRUE.equals(request.smsConsent()));
        return MarketingConsentResponse.from(lead);
    }

    private AppUser currentUser(Authentication authentication) {
        return userRepository.findByEmailIgnoreCase(authentication.getName())
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Sesja wygasła"));
    }

    public record MarketingConsentRequest(
            @NotNull Boolean emailConsent,
            @NotNull Boolean smsConsent
    ) {
    }

    public record MarketingConsentResponse(
            boolean emailConsent,
            boolean smsConsent,
            boolean emailOptOut,
            boolean smsOptOut
    ) {
        static MarketingConsentResponse from(Lead lead) {
            return new MarketingConsentResponse(
                    lead.isEmailConsent(),
                    lead.isSmsConsent(),
                    lead.isEmailOptOut(),
                    lead.isSmsOptOut()
            );
        }
    }
}
