package pl.polskalokalnie.unsubscribe;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Publiczny endpoint rezygnacji - link z tokenem doklejany do kazdej wiadomosci marketingowej.
 * Musi byc na liscie permitAll w SecurityConfig. Zwraca prosta strone potwierdzenia po polsku.
 */
@RestController
@RequestMapping("/api/unsubscribe")
public class UnsubscribeController {

    private final UnsubscribeService unsubscribeService;

    public UnsubscribeController(UnsubscribeService unsubscribeService) {
        this.unsubscribeService = unsubscribeService;
    }

    @GetMapping(produces = MediaType.TEXT_HTML_VALUE)
    public String unsubscribe(@RequestParam("token") String token) {
        UnsubscribeService.Result result = unsubscribeService.unsubscribe(token);
        String kanal = "sms".equals(result.channel()) ? "SMS" : "e-mail";
        return page("Rezygnacja przyjęta",
                "Twój adres" + (result.maskedContact().isEmpty() ? "" : " (" + result.maskedContact() + ")")
                        + " został wypisany z wiadomości marketingowych (" + kanal + "). "
                        + "Nie będziemy już wysyłać Ci kampanii tym kanałem.");
    }

    private static String page(String title, String message) {
        return "<!doctype html><html lang=\"pl\"><head><meta charset=\"utf-8\">"
                + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
                + "<title>" + title + "</title>"
                + "<style>body{font-family:system-ui,Segoe UI,Arial,sans-serif;background:#f5f6fa;margin:0;"
                + "display:flex;min-height:100vh;align-items:center;justify-content:center;padding:24px}"
                + ".card{background:#fff;max-width:460px;padding:36px 32px;border-radius:16px;"
                + "box-shadow:0 12px 40px rgba(15,23,42,.12);text-align:center}"
                + "h1{font-size:20px;color:#0f172a;margin:0 0 12px}p{color:#475569;line-height:1.6;margin:0}</style>"
                + "</head><body><div class=\"card\"><h1>" + title + "</h1><p>" + message + "</p></div></body></html>";
    }
}
