package sqlite

import (
	"context"
	"database/sql"
)

// ── Mention resolution (v0.29.0) ────────────────────────────────────────

func (s *CatalogStore) FindEnabledByModelID(ctx context.Context, modelID string) (string, string, error) {
	var foundModelID, configID string
	err := DB.QueryRowContext(ctx, `
		SELECT mc.model_id, mc.provider_config_id
		FROM model_catalog mc
		JOIN provider_configs pc ON pc.id = mc.provider_config_id
		WHERE LOWER(mc.model_id) = LOWER(?)
		  AND mc.visibility = 'enabled'
		  AND pc.is_active = 1
		ORDER BY
			CASE pc.scope WHEN 'global' THEN 0 WHEN 'team' THEN 1 WHEN 'personal' THEN 2 END
		LIMIT 1
	`, modelID).Scan(&foundModelID, &configID)
	if err == sql.ErrNoRows {
		return "", "", nil
	}
	return foundModelID, configID, err
}

func (s *CatalogStore) FindEnabledByModelIDPrefix(ctx context.Context, prefix string) (string, string, int, error) {
	var count int
	err := DB.QueryRowContext(ctx, `
		SELECT COUNT(DISTINCT mc.model_id)
		FROM model_catalog mc
		JOIN provider_configs pc ON pc.id = mc.provider_config_id
		WHERE LOWER(mc.model_id) LIKE LOWER(?)
		  AND mc.visibility = 'enabled'
		  AND pc.is_active = 1
	`, prefix+"%").Scan(&count)
	if err != nil {
		return "", "", 0, err
	}
	if count != 1 {
		return "", "", count, nil
	}
	var foundModelID, configID string
	err = DB.QueryRowContext(ctx, `
		SELECT mc.model_id, mc.provider_config_id
		FROM model_catalog mc
		JOIN provider_configs pc ON pc.id = mc.provider_config_id
		WHERE LOWER(mc.model_id) LIKE LOWER(?)
		  AND mc.visibility = 'enabled'
		  AND pc.is_active = 1
		ORDER BY CASE pc.scope WHEN 'global' THEN 0 WHEN 'team' THEN 1 WHEN 'personal' THEN 2 END
		LIMIT 1
	`, prefix+"%").Scan(&foundModelID, &configID)
	return foundModelID, configID, 1, err
}
