package bot

import (
	"context"
	"fmt"
	"log"

	"github.com/mymmrac/telego"
)

// handleSubscribe adds the requesting chat to the subscribers table.
// If the chat is already subscribed, it informs the user without error.
func (b *Bot) handleSubscribe(ctx context.Context, msg *telego.Message) {
	chatID := msg.Chat.ID
	var username string
	if msg.From != nil {
		username = msg.From.Username
	}

	subscribed, err := b.cfg.DB.IsSubscribed(chatID)
	if err != nil {
		log.Printf("subscribe: checking subscription for chat %d: %v", chatID, err)
		_ = b.replyPlain(ctx, chatID, "Error checking subscription status. Please try again.")
		return
	}

	if subscribed {
		_ = b.replyPlain(ctx, chatID, "You are already subscribed to notifications.")
		return
	}

	if err := b.cfg.DB.AddSubscriber(chatID, username); err != nil {
		log.Printf("subscribe: adding subscriber chat %d: %v", chatID, err)
		_ = b.replyPlain(ctx, chatID, fmt.Sprintf("Error subscribing: %v", err))
		return
	}

	_ = b.replyPlain(ctx, chatID, "Subscribed! You will receive notifications when new API keys are found.")
}

// handleUnsubscribe removes the requesting chat from the subscribers table.
// If the chat was not subscribed, it informs the user without error.
func (b *Bot) handleUnsubscribe(ctx context.Context, msg *telego.Message) {
	chatID := msg.Chat.ID

	rows, err := b.cfg.DB.RemoveSubscriber(chatID)
	if err != nil {
		log.Printf("unsubscribe: removing subscriber chat %d: %v", chatID, err)
		_ = b.replyPlain(ctx, chatID, fmt.Sprintf("Error unsubscribing: %v", err))
		return
	}

	if rows == 0 {
		_ = b.replyPlain(ctx, chatID, "You are not subscribed.")
		return
	}

	_ = b.replyPlain(ctx, chatID, "Unsubscribed. You will no longer receive notifications.")
}
