package connectorreaders

import (
	"database/sql"
	"fmt"
	"strings"

	apperrors "github.com/nexuscrm/kernel/pkg/errors"
)

// flowSourceStandard is the Source value stamped on pack-owned standard Flow
// versions. Kept here (mirroring the seeder copy) because the active-version
// guard below compares against it.
const flowSourceStandard = "standard"

// StandardFlowActiveVersionIsPackOwned is the runtime counterpart of the
// seeder's active-version guard. It returns true only when the named
// FlowDefinition is still pack-owned and its active Flow version is a
// Source='standard' row. Callers use this before applying L1-only privileges
// that were reviewed against the shipped standard flow graph.
func StandardFlowActiveVersionIsPackOwned(db *sql.DB, developerName string) (bool, error) {
	if db == nil || strings.TrimSpace(developerName) == "" {
		return false, nil
	}
	var isCustomized sql.NullBool
	var src sql.NullString
	err := db.QueryRow(
		`SELECT fd.IsCustomized, f.Source
		   FROM FlowDefinition fd
		   LEFT JOIN Flow f ON f.Id = fd.ActiveVersionId AND f.IsDeleted = 0
		  WHERE fd.DeveloperName = ? AND fd.IsDeleted = 0
		  LIMIT 1`,
		developerName,
	).Scan(&isCustomized, &src)
	switch {
	case err == sql.ErrNoRows:
		return false, nil
	case err != nil:
		return false, apperrors.NewInternalError(fmt.Sprintf("lookup active Flow source for %q", developerName), err)
	}
	if isCustomized.Valid && isCustomized.Bool {
		return false, nil
	}
	if !src.Valid {
		return false, nil
	}
	return src.String == flowSourceStandard, nil
}
