package storage

import "time"

// Subscriber represents a Telegram chat subscribed to scan notifications.
type Subscriber struct {
	ChatID       int64
	Username     string
	SubscribedAt time.Time
}

// AddSubscriber inserts or replaces a subscriber in the database.
func (db *DB) AddSubscriber(chatID int64, username string) error {
	_, err := db.sql.Exec(
		`INSERT OR REPLACE INTO subscribers (chat_id, username, subscribed_at) VALUES (?, ?, CURRENT_TIMESTAMP)`,
		chatID, username,
	)
	return err
}

// RemoveSubscriber deletes a subscriber by chat ID. Returns rows affected.
func (db *DB) RemoveSubscriber(chatID int64) (int64, error) {
	res, err := db.sql.Exec(`DELETE FROM subscribers WHERE chat_id = ?`, chatID)
	if err != nil {
		return 0, err
	}
	return res.RowsAffected()
}

// ListSubscribers returns all subscribers ordered by subscription time.
func (db *DB) ListSubscribers() ([]Subscriber, error) {
	rows, err := db.sql.Query(`SELECT chat_id, username, subscribed_at FROM subscribers ORDER BY subscribed_at`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var subs []Subscriber
	for rows.Next() {
		var s Subscriber
		if err := rows.Scan(&s.ChatID, &s.Username, &s.SubscribedAt); err != nil {
			return nil, err
		}
		subs = append(subs, s)
	}
	return subs, rows.Err()
}

// IsSubscribed returns true if the given chat ID is subscribed.
func (db *DB) IsSubscribed(chatID int64) (bool, error) {
	var count int
	err := db.sql.QueryRow(`SELECT COUNT(*) FROM subscribers WHERE chat_id = ?`, chatID).Scan(&count)
	return count > 0, err
}
