package message

import (
	"context"
	"strings"

	"github.com/tidbcloud/AgentTeam/internal/coredb"
)

type fakeContributionSourceQueryer struct {
	query        string
	args         []any
	queries      []string
	argsList     [][]any
	nativeRows   *fakeContributionSourceRows
	workflowRows *fakeContributionSourceRows
	scheduleRows *fakeContributionSourceRows
	defaultRows  *fakeContributionSourceRows
}

func (queryer *fakeContributionSourceQueryer) QueryRow(context.Context, string, ...any) coredb.Row {
	return nil
}

func (queryer *fakeContributionSourceQueryer) Query(_ context.Context, query string, args ...any) (coredb.Rows, error) {
	normalized := strings.Join(strings.Fields(query), " ")
	queryer.query = normalized
	queryer.args = append([]any(nil), args...)
	queryer.queries = append(queryer.queries, normalized)
	queryer.argsList = append(queryer.argsList, append([]any(nil), args...))
	switch {
	case strings.Contains(normalized, "service_event_deliveries"):
		if queryer.nativeRows == nil {
			queryer.nativeRows = &fakeContributionSourceRows{}
		}
		return queryer.nativeRows, nil
	case strings.Contains(normalized, "workflow_run_effects"):
		if queryer.workflowRows == nil {
			queryer.workflowRows = &fakeContributionSourceRows{}
		}
		return queryer.workflowRows, nil
	case strings.Contains(normalized, "automation_runs"):
		if queryer.scheduleRows == nil {
			queryer.scheduleRows = &fakeContributionSourceRows{}
		}
		return queryer.scheduleRows, nil
	default:
		if queryer.defaultRows == nil {
			queryer.defaultRows = &fakeContributionSourceRows{}
		}
		return queryer.defaultRows, nil
	}
}

type fakeContributionSourceRows struct {
	values [][]any
	idx    int
	closed bool
}

func (rows *fakeContributionSourceRows) Close()     { rows.closed = true }
func (rows *fakeContributionSourceRows) Err() error { return nil }
func (rows *fakeContributionSourceRows) Next() bool {
	if rows.idx >= len(rows.values) {
		return false
	}
	rows.idx++
	return true
}
func (rows *fakeContributionSourceRows) Scan(dest ...any) error {
	current := rows.values[rows.idx-1]
	for i := range dest {
		ptr := dest[i].(*string)
		*ptr = current[i].(string)
	}
	return nil
}
