package babble

import (
	"fmt"
	"strings"
	"time"

	"dk/internal/database"
)

// Babble represents a global chat message in the game
type Babble struct {
	ID     int
	Posted int64
	Author int
	Babble string
}

// New creates a new Babble with sensible defaults
func New() *Babble {
	return &Babble{
		Posted: time.Now().Unix(),
		Author: 0,
		Babble: "",
	}
}

// Validate checks if babble has valid values
func (b *Babble) Validate() error {
	if b.Posted <= 0 {
		return fmt.Errorf("babble Posted timestamp must be positive")
	}
	if b.Author <= 0 {
		return fmt.Errorf("babble Author must be a valid user ID")
	}
	if strings.TrimSpace(b.Babble) == "" {
		return fmt.Errorf("babble message cannot be empty")
	}
	return nil
}

func (b *Babble) Delete() error {
	return database.Exec("DELETE FROM babble WHERE id = %d", b.ID)
}

func (b *Babble) Insert() error {
	id, err := database.Insert("babble", b, "ID")
	if err != nil {
		return err
	}
	b.ID = int(id)
	return nil
}

func Find(id int) (*Babble, error) {
	var babble Babble
	err := database.Get(&babble, "SELECT * FROM babble WHERE id = %d", id)
	if err != nil {
		return nil, fmt.Errorf("babble with ID %d not found", id)
	}
	return &babble, nil
}

func All() ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble ORDER BY posted DESC, id DESC")
	return babbles, err
}

func ByAuthor(authorID int) ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble WHERE author = %d ORDER BY posted DESC, id DESC", authorID)
	return babbles, err
}

func Recent(limit int) ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble ORDER BY posted DESC, id DESC LIMIT %d", limit)
	return babbles, err
}

func Since(since int64) ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble WHERE posted >= %d ORDER BY posted DESC, id DESC", since)
	return babbles, err
}

func Between(start, end int64) ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble WHERE posted >= %d AND posted <= %d ORDER BY posted DESC, id DESC", start, end)
	return babbles, err
}

func Search(term string) ([]*Babble, error) {
	var babbles []*Babble
	searchTerm := "%" + term + "%"
	err := database.Select(&babbles, "SELECT * FROM babble WHERE babble LIKE %s ORDER BY posted DESC, id DESC", searchTerm)
	return babbles, err
}

func RecentByAuthor(authorID int, limit int) ([]*Babble, error) {
	var babbles []*Babble
	err := database.Select(&babbles, "SELECT * FROM babble ORDER BY posted DESC, id DESC LIMIT %d", authorID, limit)
	return babbles, err
}

func (b *Babble) PostedTime() time.Time {
	return time.Unix(b.Posted, 0)
}

func (b *Babble) SetPostedTime(t time.Time) {
	b.Posted = t.Unix()
}

func (b *Babble) IsRecent() bool {
	return time.Since(b.PostedTime()) < time.Hour
}

func (b *Babble) Age() time.Duration {
	return time.Since(b.PostedTime())
}

func (b *Babble) IsAuthor(userID int) bool {
	return b.Author == userID
}

func (b *Babble) Preview(maxLength int) string {
	if len(b.Babble) <= maxLength {
		return b.Babble
	}

	if maxLength < 3 {
		return b.Babble[:maxLength]
	}

	return b.Babble[:maxLength-3] + "..."
}

func (b *Babble) WordCount() int {
	if b.Babble == "" {
		return 0
	}

	// Simple word count by splitting on whitespace
	words := 0
	inWord := false

	for _, char := range b.Babble {
		if char == ' ' || char == '\t' || char == '\n' || char == '\r' {
			if inWord {
				words++
				inWord = false
			}
		} else {
			inWord = true
		}
	}

	if inWord {
		words++
	}

	return words
}

func (b *Babble) Length() int {
	return len(b.Babble)
}

func (b *Babble) Contains(term string) bool {
	return strings.Contains(strings.ToLower(b.Babble), strings.ToLower(term))
}

func (b *Babble) IsEmpty() bool {
	return strings.TrimSpace(b.Babble) == ""
}

func (b *Babble) IsLongMessage(threshold int) bool {
	return b.Length() > threshold
}

func (b *Babble) GetMentions() []string {
	words := strings.Fields(b.Babble)
	var mentions []string

	for _, word := range words {
		if strings.HasPrefix(word, "@") && len(word) > 1 {
			// Clean up punctuation from the end
			mention := strings.TrimRight(word[1:], ".,!?;:")
			if mention != "" {
				mentions = append(mentions, mention)
			}
		}
	}

	return mentions
}

func (b *Babble) HasMention(username string) bool {
	mentions := b.GetMentions()
	for _, mention := range mentions {
		if strings.EqualFold(mention, username) {
			return true
		}
	}
	return false
}
