defmodule BerrypodWeb.UnsubscribeController do
  use BerrypodWeb, :controller

  alias Berrypod.{Newsletter, Orders}

  # Unsubscribe links should be long-lived — use 2 years
  @max_age 2 * 365 * 24 * 3600

  def unsubscribe(conn, %{"token" => token}) do
    case Phoenix.Token.verify(BerrypodWeb.Endpoint, "email-unsub", token, max_age: @max_age) do
      {:ok, email} ->
        Orders.add_suppression(email, "unsubscribed")
        Newsletter.unsubscribe(email)

        conn
        |> put_status(200)
        |> html("""
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Unsubscribed</title>
          <style>body{font-family:system-ui,sans-serif;max-width:480px;margin:80px auto;padding:0 24px;color:#111}</style>
        </head>
        <body>
          <h1 style="font-size:1.25rem;margin-bottom:0.75rem">You've been unsubscribed</h1>
          <p style="color:#555">We've removed #{email} from our marketing emails. You won't hear from us again.</p>
        </body>
        </html>
        """)

      {:error, _reason} ->
        conn
        |> put_status(400)
        |> html("""
        <!DOCTYPE html>
        <html lang="en">
        <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Invalid link</title>
          <style>body{font-family:system-ui,sans-serif;max-width:480px;margin:80px auto;padding:0 24px;color:#111}</style>
        </head>
        <body>
          <h1 style="font-size:1.25rem;margin-bottom:0.75rem">Link invalid or expired</h1>
          <p style="color:#555">This unsubscribe link has expired or is invalid. If you'd like to unsubscribe, reply to any email we've sent you.</p>
        </body>
        </html>
        """)
    end
  end
end
