package com.example.dateplanner.controllers.web;

import com.example.dateplanner.models.entities.AppUser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseWebController {

    @Value("${minio.cdn}")
    private String cdnUrl;

    @Value("${turnstile.site-key:}")
    private String turnstileSiteKey;

    protected Mono<Map<String, Object>> addAuthToModel(Map<String, Object> model) {
        return ReactiveSecurityContextHolder.getContext()
                .map(ctx -> {
                    var authentication = ctx.getAuthentication();
                    if (authentication != null && authentication.isAuthenticated()
                            && authentication.getPrincipal() instanceof AppUser user) {
                        model.put("auth", true);
                        Map<String, Object> userMap = new HashMap<>();
                        userMap.put("uuid", user.getUuid() != null ? user.getUuid().toString() : null);
                        userMap.put("email", user.getPhone());
                        userMap.put("firstName", user.getFirstName());
                        userMap.put("lastName", user.getLastName());
                        userMap.put("role", user.getRole() != null ? user.getRole().toString() : null);
                        model.put("user", userMap);
                    } else {
                        model.put("auth", false);
                        model.put("user", null);
                    }
                    model.put("cdn", cdnUrl != null ? cdnUrl : "");
                    model.put("turnstileSiteKey", turnstileSiteKey != null ? turnstileSiteKey : "");
                    return model;
                })
                .switchIfEmpty(Mono.fromCallable(() -> {
                    model.put("auth", false);
                    model.put("user", null);
                    model.put("cdn", cdnUrl != null ? cdnUrl : "");
                    model.put("turnstileSiteKey", turnstileSiteKey != null ? turnstileSiteKey : "");
                    return model;
                }));
    }
}
