package layoutrouting

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/nexuscrm/shared/pkg/constants"
)

// WildcardTarget is the oldest wildcard assignment that still points at a
// live target layout for an object, joined with the target layout's ownership
// markers.
type WildcardTarget struct {
	AssignmentID  string
	LayoutID      string
	Source        string
	IsCustomized  bool
	TargetPresent bool
	RouteSource   *string
}

// LoadLiveWildcardTarget is the single reader for effective default layout
// routing. Runtime and control-plane callers must share this helper so the
// wildcard assignment remains the only read path for the routing fact.
func LoadLiveWildcardTarget(ctx context.Context, db *sql.DB, objectAPIName string) (*WildcardTarget, error) {
	query := fmt.Sprintf(
		"SELECT la.`Id`, la.`LayoutId`, COALESCE(pl.`%s`, ''), COALESCE(pl.`%s`, 0), 1, la.`RouteSource` "+
			"FROM `%s` la "+
			"JOIN `%s` pl ON pl.`%s` = la.`LayoutId` "+
			"AND LOWER(pl.`%s`) = LOWER(la.`ObjectApiName`) "+
			"AND (pl.`%s` = 0 OR pl.`%s` IS NULL) "+
			"WHERE LOWER(la.`ObjectApiName`) = LOWER(?) AND la.`RoleId` IS NULL AND la.`ProfileId` IS NULL AND la.`RecordTypeId` IS NULL "+
			"ORDER BY la.`CreatedDate` ASC LIMIT 1",
		constants.FieldSysPageLayout_Source,
		constants.FieldSysPageLayout_IsCustomized,
		constants.TableLayoutAssignment,
		constants.TablePageLayout,
		constants.ColID,
		constants.FieldObjectAPIName,
		constants.FieldIsDeleted,
		constants.FieldIsDeleted,
	)

	var target WildcardTarget
	var routeSource sql.NullString
	if err := db.QueryRowContext(ctx, query, objectAPIName).Scan(
		&target.AssignmentID,
		&target.LayoutID,
		&target.Source,
		&target.IsCustomized,
		&target.TargetPresent,
		&routeSource,
	); err != nil {
		if err == sql.ErrNoRows {
			return nil, nil
		}
		return nil, err
	}
	if routeSource.Valid {
		target.RouteSource = &routeSource.String
	}
	return &target, nil
}
