package com.smyhub.store.mengyastorebackendjava.service;

import com.smyhub.store.mengyastorebackendjava.dto.request.SmtpConfigRequest;
import com.smyhub.store.mengyastorebackendjava.dto.response.MaintenanceResponse;
import com.smyhub.store.mengyastorebackendjava.dto.response.SmtpConfigResponse;
import com.smyhub.store.mengyastorebackendjava.entity.SiteSetting;
import com.smyhub.store.mengyastorebackendjava.repository.SiteSettingRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class SiteService {

    private static final String KEY_TOTAL_VISITS = "totalVisits";
    private static final String KEY_MAINTENANCE = "maintenance";
    private static final String KEY_MAINTENANCE_REASON = "maintenanceReason";
    private static final String KEY_SMTP_ENABLED = "smtpEnabled";
    private static final String KEY_SMTP_EMAIL = "smtpEmail";
    private static final String KEY_SMTP_PASSWORD = "smtpPassword";
    private static final String KEY_SMTP_FROM_NAME = "smtpFromName";
    private static final String KEY_SMTP_HOST = "smtpHost";
    private static final String KEY_SMTP_PORT = "smtpPort";

    private final SiteSettingRepository repo;

    private String get(String key) {
        return repo.findById(key).map(SiteSetting::getValue).orElse(null);
    }

    private void set(String key, String value) {
        repo.save(new SiteSetting(key, value));
    }

    public int getTotalVisits() {
        String v = get(KEY_TOTAL_VISITS);
        if (v == null || v.isBlank()) return 0;
        try { return Integer.parseInt(v); } catch (NumberFormatException e) { return 0; }
    }

    @Transactional
    public int incrementVisits() {
        int current = getTotalVisits() + 1;
        set(KEY_TOTAL_VISITS, String.valueOf(current));
        return current;
    }

    public MaintenanceResponse getMaintenance() {
        String enabled = get(KEY_MAINTENANCE);
        String reason = get(KEY_MAINTENANCE_REASON);
        return MaintenanceResponse.builder()
                .maintenance("true".equals(enabled))
                .reason(reason != null ? reason : "")
                .build();
    }

    @Transactional
    public void setMaintenance(boolean enabled, String reason) {
        set(KEY_MAINTENANCE, enabled ? "true" : "false");
        set(KEY_MAINTENANCE_REASON, reason != null ? reason : "");
    }

    public SmtpConfig getSmtpConfig() {
        SmtpConfig cfg = new SmtpConfig();
        String enabledStr = get(KEY_SMTP_ENABLED);
        cfg.enabled = !"false".equals(enabledStr);
        cfg.email = nvl(get(KEY_SMTP_EMAIL), "");
        cfg.password = nvl(get(KEY_SMTP_PASSWORD), "");
        cfg.fromName = nvl(get(KEY_SMTP_FROM_NAME), "萌芽小店");
        cfg.host = nvl(get(KEY_SMTP_HOST), "smtp.qq.com");
        cfg.port = nvl(get(KEY_SMTP_PORT), "465");
        return cfg;
    }

    @Transactional
    public void setSmtpConfig(SmtpConfigRequest req) {
        set(KEY_SMTP_ENABLED, req.isEnabled() ? "true" : "false");
        set(KEY_SMTP_EMAIL, nvl(req.getEmail(), ""));
        set(KEY_SMTP_PASSWORD, nvl(req.getPassword(), ""));
        set(KEY_SMTP_FROM_NAME, nvl(req.getFromName(), ""));
        set(KEY_SMTP_HOST, nvl(req.getHost(), "smtp.qq.com"));
        set(KEY_SMTP_PORT, nvl(req.getPort(), "465"));
    }

    public SmtpConfigResponse getSmtpConfigResponse(boolean maskPassword) {
        SmtpConfig cfg = getSmtpConfig();
        return SmtpConfigResponse.builder()
                .enabled(cfg.enabled)
                .email(cfg.email)
                .password(maskPassword ? maskStr(cfg.password) : cfg.password)
                .fromName(cfg.fromName)
                .host(cfg.host)
                .port(cfg.port)
                .build();
    }

    private static String nvl(String s, String def) {
        return (s != null && !s.isBlank()) ? s : def;
    }

    private static String maskStr(String s) {
        if (s == null || s.length() <= 2) return "***";
        return s.substring(0, 1) + "***" + s.substring(s.length() - 1);
    }

    public static class SmtpConfig {
        public boolean enabled = true;
        public String email = "";
        public String password = "";
        public String fromName = "萌芽小店";
        public String host = "smtp.qq.com";
        public String port = "465";

        public boolean isConfigured() {
            return enabled && !email.isBlank() && !password.isBlank() && !host.isBlank();
        }
    }
}
