package bot

import (
	"database/sql"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"

	"github.com/z/tg-apicreator-bot/internal/i18n"
)

// guard is the shared access-control gate. It returns the resolved user,
// their language bundle and an optional "deny" message that the caller should
// send and then return. When allow==false the caller must stop processing.
func (b *Bot) guard(update tgbotapi.Update) (allow bool, denyText string, lang i18n.Lang) {
	uid := userIDOf(update)
	if uid == 0 {
		return false, "", i18n.Fa
	}

	// Admins always pass, even in whitelist mode or if marked banned.
	if b.cfg.IsAdmin(uid) {
		lang = i18n.Normalize(b.cfg.Bot.DefaultLanguage)
		if u, err := b.repo.GetUserByTgID(uid); err == nil {
			lang = i18n.Normalize(u.Language)
		}
		return true, "", lang
	}

	u, err := b.repo.GetUserByTgID(uid)
	if err != nil {
		// First interaction: store a skeleton user so we can ban/track them.
		_, _ = b.repo.UpsertUser(b.newUserFromUpdate(update, b.cfg.IsAdmin(uid)))
		u, err = b.repo.GetUserByTgID(uid)
		if err != nil {
			return false, i18n.Get(i18n.Fa).NotAuthorized, i18n.Fa
		}
	}
	lang = i18n.Normalize(u.Language)

	if u.IsBanned {
		return false, i18n.Get(lang).Banned, lang
	}
	if b.cfg.Bot.WhitelistEnabled && !b.cfg.IsAdmin(uid) {
		allowed := false
		for _, w := range b.cfg.Bot.Whitelist {
			if w == uid {
				allowed = true
				break
			}
		}
		if !allowed {
			return false, i18n.Get(lang).WhitelistOnly, lang
		}
	}
	return true, "", lang
}

// userIDOf extracts the Telegram user id from any kind of update.
func userIDOf(update tgbotapi.Update) int64 {
	switch {
	case update.Message != nil && update.Message.From != nil:
		return update.Message.From.ID
	case update.CallbackQuery != nil && update.CallbackQuery.From != nil:
		return update.CallbackQuery.From.ID
	case update.EditedMessage != nil && update.EditedMessage.From != nil:
		return update.EditedMessage.From.ID
	}
	return 0
}

// chatIDOf extracts the chat id for replying.
func chatIDOf(update tgbotapi.Update) int64 {
	switch {
	case update.Message != nil:
		return update.Message.Chat.ID
	case update.CallbackQuery != nil && update.CallbackQuery.Message != nil:
		return update.CallbackQuery.Message.Chat.ID
	case update.EditedMessage != nil:
		return update.EditedMessage.Chat.ID
	}
	return 0
}

// reply sends a HTML message to the update's chat. Errors are logged, not
// surfaced, so a handler can keep going.
func (b *Bot) reply(chatID int64, text string) {
	if chatID == 0 || text == "" {
		return
	}
	msg := tgbotapi.NewMessage(chatID, text)
	msg.ParseMode = "HTML"
	msg.DisableWebPagePreview = true
	if _, err := b.api.Send(msg); err != nil {
		b.logf("warn", "send message failed: %v", err)
	}
}

// answerCallback acks a callback query so the spinner stops.
func (b *Bot) answerCallback(id string, text string) {
	if id == "" {
		return
	}
	cb := tgbotapi.NewCallback(id, text)
	if _, err := b.api.Request(cb); err != nil {
		b.logf("warn", "answer callback failed: %v", err)
	}
}

// nullInt helper for log rows.
func nullInt(i int64) sql.NullInt64 {
	if i == 0 {
		return sql.NullInt64{}
	}
	return sql.NullInt64{Int64: i, Valid: true}
}
