package postgres

import (
	"context"
	"database/sql"

	"chat-switchboard/store"
)

// ── Mention resolution + display info (v0.29.0) ────────────────────────

func (s *UserStore) FindActiveByHandle(ctx context.Context, handle, excludeUserID string) (string, error) {
	var id string
	err := DB.QueryRowContext(ctx, `
		SELECT id FROM users
		WHERE LOWER(handle) = LOWER($1) AND id != $2 AND is_active = true
		LIMIT 1
	`, handle, excludeUserID).Scan(&id)
	if err == sql.ErrNoRows {
		return "", nil
	}
	return id, err
}

func (s *UserStore) FindActiveByHandlePrefix(ctx context.Context, prefix, excludeUserID string) (string, int, error) {
	var count int
	err := DB.QueryRowContext(ctx, `
		SELECT COUNT(*) FROM users
		WHERE LOWER(handle) LIKE LOWER($1) AND id != $2 AND is_active = true
	`, prefix+"%", excludeUserID).Scan(&count)
	if err != nil {
		return "", 0, err
	}
	if count != 1 {
		return "", count, nil
	}
	var id string
	err = DB.QueryRowContext(ctx, `
		SELECT id FROM users
		WHERE LOWER(handle) LIKE LOWER($1) AND id != $2 AND is_active = true
		LIMIT 1
	`, prefix+"%", excludeUserID).Scan(&id)
	return id, 1, err
}

func (s *UserStore) GetDisplayInfoByIDs(ctx context.Context, ids []string) (map[string]store.UserDisplayInfo, error) {
	result := make(map[string]store.UserDisplayInfo)
	for _, id := range ids {
		var name, avatar sql.NullString
		_ = DB.QueryRowContext(ctx, `
			SELECT COALESCE(display_name, username), avatar_url FROM users WHERE id = $1
		`, id).Scan(&name, &avatar)
		if name.Valid {
			info := store.UserDisplayInfo{Name: name.String}
			if avatar.Valid {
				info.Avatar = avatar.String
			}
			result[id] = info
		}
	}
	return result, nil
}
