// Package botlink is the bot side of the reverse Telegram channel: the bot dials
// the gateway over mTLS (pkg/proto/botlink/v1), opens one long-lived Link stream,
// and executes the send Commands the gateway pushes, replying with an Ack per
// command. It keeps the Bot API token and egress on the remote bot host with no
// inbound port. See docs/ARCHITECTURE.md.
package botlink

import (
	"context"
	"fmt"
	"strconv"

	"go.uber.org/zap"

	botlinkv1 "scrabble/pkg/proto/botlink/v1"
	telegramv1 "scrabble/pkg/proto/telegram/v1"
	"scrabble/platform/telegram/internal/render"
)

// Sender delivers Telegram messages to a chat. *bot.Bot implements it.
type Sender interface {
	// Notify sends a notification with a Mini App launch button to chatID.
	Notify(ctx context.Context, chatID int64, text, buttonText, startParam string) error
	// SendText sends a plain text message to chatID.
	SendText(ctx context.Context, chatID int64, text string) error
	// ApplyChatGate sets the Telegram user's write access in the moderated discussion
	// chat, but only when they are currently in it; it reports whether a restriction
	// was applied.
	ApplyChatGate(ctx context.Context, userID int64, allow bool) (bool, error)
	// CreateInvoiceLink mints a Telegram Stars invoice link (XTR) for amountStars, tagged
	// with payload (the order id, echoed back in pre_checkout and successful_payment), and
	// returns the link.
	CreateInvoiceLink(ctx context.Context, title, description, payload string, amountStars int64) (string, error)
}

// Executor turns a bot-link Command into a Bot API send. The delivered flag mirrors
// the former connector semantics (false when the kind is not rendered out-of-app,
// the user never started the bot, or no channel is configured); a returned error is
// an unexpected or malformed failure carried back in the Ack error field, distinct
// from a clean not-delivered.
type Executor struct {
	sender    Sender
	channelID int64
	log       *zap.Logger
}

// NewExecutor builds the executor over a bot sender and the optional game channel.
func NewExecutor(sender Sender, channelID int64, log *zap.Logger) *Executor {
	if log == nil {
		log = zap.NewNop()
	}
	return &Executor{sender: sender, channelID: channelID, log: log}
}

// Handle dispatches one command to the matching Bot API call. It returns whether the command was
// delivered, an optional result string (the created invoice link for a create_invoice command; empty
// otherwise), and an error for an unexpected or malformed failure.
func (e *Executor) Handle(ctx context.Context, cmd *botlinkv1.Command) (bool, string, error) {
	switch p := cmd.GetPayload().(type) {
	case *botlinkv1.Command_Notify:
		d, err := e.notify(ctx, p.Notify)
		return d, "", err
	case *botlinkv1.Command_SendToUser:
		d, err := e.sendToUser(ctx, p.SendToUser)
		return d, "", err
	case *botlinkv1.Command_SendToChannel:
		d, err := e.sendToChannel(ctx, p.SendToChannel)
		return d, "", err
	case *botlinkv1.Command_ChatGate:
		d, err := e.chatGate(ctx, p.ChatGate)
		return d, "", err
	case *botlinkv1.Command_CreateInvoice:
		return e.createInvoice(ctx, p.CreateInvoice)
	default:
		return false, "", fmt.Errorf("botlink: empty command")
	}
}

// createInvoice mints a Telegram Stars invoice link for the order and returns it in the Ack result.
// A Bot API failure is a hard error carried back in the Ack, so the gateway's synchronous mint fails
// (rather than returning an empty link).
func (e *Executor) createInvoice(ctx context.Context, req *botlinkv1.CreateInvoiceCommand) (bool, string, error) {
	link, err := e.sender.CreateInvoiceLink(ctx, req.GetTitle(), req.GetDescription(), req.GetPayload(), req.GetAmount())
	if err != nil {
		e.log.Warn("create invoice link failed", zap.String("order", req.GetPayload()), zap.Error(err))
		return false, "", err
	}
	return true, link, nil
}

// chatGate applies a chat-gate command: it parses the target Telegram user id and
// sets their write access in the moderated chat (a no-op when they are not in it). A
// Bot API failure is logged and reported as not-delivered, not a hard error.
func (e *Executor) chatGate(ctx context.Context, req *botlinkv1.ChatGateCommand) (bool, error) {
	userID, err := parseChatID(req.GetExternalId())
	if err != nil {
		return false, err
	}
	applied, err := e.sender.ApplyChatGate(ctx, userID, req.GetAllow())
	if err != nil {
		e.log.Warn("chat gate apply failed",
			zap.String("external_id", req.GetExternalId()), zap.Bool("allow", req.GetAllow()), zap.Error(err))
		return false, nil
	}
	return applied, nil
}

// notify renders an out-of-app push and sends it with a Mini App launch button.
func (e *Executor) notify(ctx context.Context, req *telegramv1.NotifyRequest) (bool, error) {
	msg, ok := render.Render(req.GetKind(), req.GetPayload(), req.GetLanguage())
	if !ok {
		return false, nil
	}
	chat, err := parseChatID(req.GetExternalId())
	if err != nil {
		return false, err
	}
	if err := e.sender.Notify(ctx, chat, msg.Text, msg.ButtonText, msg.StartParam); err != nil {
		e.log.Warn("notify delivery failed", zap.String("kind", req.GetKind()), zap.Error(err))
		return false, nil
	}
	return true, nil
}

// sendToUser sends an admin text message to one user.
func (e *Executor) sendToUser(ctx context.Context, req *telegramv1.SendToUserRequest) (bool, error) {
	chat, err := parseChatID(req.GetExternalId())
	if err != nil {
		return false, err
	}
	if err := e.sender.SendText(ctx, chat, req.GetText()); err != nil {
		e.log.Warn("send to user failed", zap.Error(err))
		return false, nil
	}
	return true, nil
}

// sendToChannel posts an admin text message to the bot's game channel.
func (e *Executor) sendToChannel(ctx context.Context, req *telegramv1.SendToGameChannelRequest) (bool, error) {
	if e.channelID == 0 {
		return false, fmt.Errorf("botlink: game channel is not configured")
	}
	if err := e.sender.SendText(ctx, e.channelID, req.GetText()); err != nil {
		e.log.Warn("send to channel failed", zap.Error(err))
		return false, nil
	}
	return true, nil
}

// parseChatID converts a Telegram identity external_id into a numeric chat id.
func parseChatID(externalID string) (int64, error) {
	id, err := strconv.ParseInt(externalID, 10, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid external_id %q", externalID)
	}
	return id, nil
}
