package notification

import "errors"

type PermanentError struct {
	Err error
}

func (e *PermanentError) Error() string {
	return e.Err.Error()
}

func (e *PermanentError) Unwrap() error {
	return e.Err
}

func NewPermanentError(err error) error {
	return &PermanentError{Err: err}
}

func IsPermanent(err error) bool {
	var permErr *PermanentError
	return errors.As(err, &permErr)
}

type Action struct {
	ID       string         `json:"id"`
	Label    string         `json:"label"`
	Endpoint string         `json:"endpoint"`
	Method   string         `json:"method"`
	Data     map[string]any `json:"data,omitempty"`
}

type Notification struct {
	Title   string   `json:"title,omitempty"`
	Message string   `json:"message"`
	Tag     string   `json:"tag,omitempty"`
	Actions []Action `json:"actions,omitempty"`
}

type Channel string

const (
	ChannelSignal   Channel = "signal"
	ChannelWebPush  Channel = "webpush"
	ChannelTelegram Channel = "telegram"
)

func (c Channel) String() string {
	return string(c)
}

func (c Channel) Label() string {
	switch c {
	case ChannelSignal:
		return "Signal"
	case ChannelWebPush:
		return "WebPush"
	case ChannelTelegram:
		return "Telegram"
	default:
		return string(c)
	}
}

func (c Channel) IsAvailable(signalEnabled bool, telegramEnabled bool) bool {
	switch c {
	case ChannelWebPush:
		return true
	case ChannelSignal:
		return signalEnabled
	case ChannelTelegram:
		return telegramEnabled
	default:
		return false
	}
}

type WebPushSubscription struct {
	Endpoint        string `json:"endpoint"`
	P256dh          string `json:"p256dh,omitempty"`
	Auth            string `json:"auth,omitempty"`
	VapidPrivateKey string `json:"vapidPrivateKey,omitempty"`
}

func (w *WebPushSubscription) HasEncryption() bool {
	return w.P256dh != "" && w.Auth != "" && w.VapidPrivateKey != ""
}

type SignalSubscription struct {
	GroupID string `json:"groupId"`
	Account string `json:"account"`
}

type TelegramSubscription struct {
	ChatID string `json:"chatId"`
}

type Subscription struct {
	ID       string                `json:"id"`
	AppName  string                `json:"appName"`
	Channel  Channel               `json:"channel"`
	Signal   *SignalSubscription   `json:"signal,omitempty"`
	WebPush  *WebPushSubscription  `json:"webPush,omitempty"`
	Telegram *TelegramSubscription `json:"telegram,omitempty"`
}

type App struct {
	AppName       string         `json:"appName"`
	Subscriptions []Subscription `json:"subscriptions"`
}
