package com.example.dateplanner.controllers.web;

import com.example.dateplanner.models.entities.AppUser;
import com.example.dateplanner.models.entities.SiteSettings;
import com.example.dateplanner.repositories.SiteSettingsRepository;
import com.example.dateplanner.services.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.result.view.Rendering;
import reactor.core.publisher.Mono;

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


@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/account")
public class AccountController extends BaseWebController {

    private final UserService userService;
    private final SiteSettingsRepository siteSettingsRepository;

    private static final String DEFAULT_BG_IMAGE =
            "https://avatars.mds.yandex.net/get-altay/1880524/2a0000016ef11d02f18395e01a44f0ddbdb7/XXL_height";

    @GetMapping("/login")
    public Mono<Rendering> loginPage() {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Login");
        model.put("index", "login");

        return siteSettingsRepository.findFirstByOrderByUpdatedAtDesc()
                .map(settings -> {
                    model.put("backgroundImageUrl",
                            settings.getBackgroundImageUrl() != null ? settings.getBackgroundImageUrl() : DEFAULT_BG_IMAGE);
                    return model;
                })
                .switchIfEmpty(Mono.fromCallable(() -> {
                    model.put("backgroundImageUrl", DEFAULT_BG_IMAGE);
                    return model;
                }))
                .flatMap(this::addAuthToModel)
                .map(m -> Rendering.view("template").model(m).build());
    }

    @GetMapping("/profile")
    public Mono<Rendering> profilePage(@AuthenticationPrincipal AppUser user) {
        Map<String, Object> model = new HashMap<>();
        model.put("title", "Profile");
        model.put("index", "admin-panel");
        return addAuthToModel(model).map(m ->
                Rendering.view("template").model(m).build()
        );
    }
}
