package de.oaa.xxx.support;

import de.oaa.xxx.social.entity.MessageCause;
import de.oaa.xxx.social.entity.MessageEntity;
import de.oaa.xxx.social.repository.MessageRepository;
import de.oaa.xxx.user.UserEntity;
import de.oaa.xxx.user.UserRepository;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Base64;
import java.util.UUID;

@Service
public class SupportUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SupportUserService.class);

    /** Deterministischer UUID – ändert sich nie. */
    public static final UUID SUPPORT_USER_ID =
            UUID.nameUUIDFromBytes("xxxsphere-support".getBytes(StandardCharsets.UTF_8));

    private static final String SUPPORT_NAME  = "xXx Support";
    private static final String SUPPORT_EMAIL = "support@system.local";

    private final UserRepository userRepository;
    private final MessageRepository messageRepository;

    public SupportUserService(UserRepository userRepository, MessageRepository messageRepository) {
        this.userRepository = userRepository;
        this.messageRepository = messageRepository;
    }

    /** Stellt sicher, dass der Support-Fake-User in der DB existiert. */
    @PostConstruct
    public void ensureExists() {
        try {
            String icon = loadIconBase64();
            userRepository.findById(SUPPORT_USER_ID).ifPresentOrElse(u -> {
                if (u.getProfilePicture() == null && icon != null) {
                    try {
                        u.setProfilePicture(icon);
                        userRepository.save(u);
                    } catch (Exception e) {
                        LOGGER.warn("Support-User-Avatar konnte nicht gespeichert werden: {}", e.getMessage());
                    }
                }
            }, () -> {
                UserEntity u = new UserEntity();
                u.setUserId(SUPPORT_USER_ID);
                u.setName(SUPPORT_NAME);
                u.setEmail(SUPPORT_EMAIL);
                u.setPassword("__SYSTEM__"); // kein gültiges Login
                try {
                    u.setProfilePicture(icon);
                    userRepository.save(u);
                } catch (Exception e) {
                    LOGGER.warn("Support-User konnte nicht mit Avatar gespeichert werden, versuche ohne: {}", e.getMessage());
                    u.setProfilePicture(null);
                    userRepository.save(u);
                }
            });
        } catch (Exception e) {
            LOGGER.error("Support-User konnte nicht initialisiert werden: {}", e.getMessage());
        }
    }

    private String loadIconBase64() {
        try {
            byte[] bytes = new ClassPathResource("static/img/icon.png").getInputStream().readAllBytes();
            BufferedImage original = ImageIO.read(new ByteArrayInputStream(bytes));
            BufferedImage thumb = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = thumb.createGraphics();
            g.drawImage(original.getScaledInstance(64, 64, Image.SCALE_SMOOTH), 0, 0, null);
            g.dispose();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(thumb, "png", baos);
            return Base64.getEncoder().encodeToString(baos.toByteArray());
        } catch (Exception e) {
            LOGGER.warn("Support-Avatar konnte nicht geladen werden: {}", e.getMessage());
            return null;
        }
    }

    /**
     * Sendet eine Direktnachricht vom Support-Account an den Nutzer.
     * Die Nachricht erscheint als normale DM (systemMessage = false),
     * damit sie in nachrichten.html sichtbar ist.
     */
    public void sendDm(UUID receiverId, String text) {
        if (receiverId == null) return;
        MessageEntity msg = new MessageEntity();
        msg.setMessageId(UUID.randomUUID());
        msg.setSenderId(SUPPORT_USER_ID);
        msg.setReceiverId(receiverId);
        msg.setText(text);
        msg.setSentAt(LocalDateTime.now());
        msg.setSystemMessage(false);
        msg.setMessageCause(MessageCause.SUPPORT);
        messageRepository.save(msg);
    }
}
