package sqlite

import (
	"context"
	"database/sql"

	"chat-switchboard/store"
)

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

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

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

func (s *PersonaStore) GetNameByID(ctx context.Context, id string) (string, error) {
	var name string
	err := DB.QueryRowContext(ctx, `SELECT name FROM personas WHERE id = ?`, id).Scan(&name)
	if err == sql.ErrNoRows {
		return "", nil
	}
	return name, err
}

func (s *PersonaStore) GetNamesByIDs(ctx context.Context, ids []string) (map[string]string, error) {
	result := make(map[string]string)
	for _, id := range ids {
		var name string
		err := DB.QueryRowContext(ctx, `SELECT name FROM personas WHERE id = ?`, id).Scan(&name)
		if err == nil && name != "" {
			result[id] = name
		}
	}
	return result, nil
}

func (s *PersonaStore) 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 name, avatar FROM personas WHERE id = ?
		`, 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
}
