package dialectsfcrm

import (
	"context"
	"errors"
	"testing"

	"github.com/nexuscrm/shared/pkg/contract"
	"github.com/nexuscrm/shared/pkg/dialect"
	"github.com/nexuscrm/shared/pkg/models"
	"github.com/nexuscrm/shared/pkg/queryspec"
)

func TestQueryWithSingleBatchSOQLLimitSkipsExactTotalSize(t *testing.T) {
	query := &windowQueryCapture{
		result: &contract.QueryResult{
			TotalSize:        2,
			TotalSizeUnknown: true,
			Done:             false,
			Records: []contract.Record{
				{"Id": "00Q1"},
				{"Id": "00Q2"},
			},
		},
	}

	resp, err := QueryNeutralHandler(context.Background(), &dialect.Request{
		Version: "v63.0",
		Query: map[string][]string{
			"q": {"SELECT Id FROM Lead ORDER BY CreatedDate DESC LIMIT 2"},
		},
		User: &models.UserSession{ID: "005-reader"},
	}, dialect.Deps{Contracts: contract.Deps{Query: query}})
	if err != nil {
		t.Fatalf("QueryNeutralHandler error = %v", err)
	}
	if resp.Status != 200 {
		t.Fatalf("status = %d, want 200; body=%#v", resp.Status, resp.Body)
	}
	if !query.spec.SkipTotalSize {
		t.Fatal("SkipTotalSize = false, want true for single-batch SOQL LIMIT window")
	}
	if query.spec.Limit != 2 || query.spec.Offset != 0 {
		t.Fatalf("query window = limit %d offset %d, want 2/0", query.spec.Limit, query.spec.Offset)
	}
	body := queryResponseBody(t, resp)
	if body["totalSize"] != 2 {
		t.Fatalf("totalSize = %#v, want 2", body["totalSize"])
	}
	if body["done"] != true {
		t.Fatalf("done = %#v, want true because the SOQL LIMIT window is exhausted", body["done"])
	}
	if _, ok := body["nextRecordsUrl"]; ok {
		t.Fatalf("nextRecordsUrl present for exhausted SOQL LIMIT window: %#v", body["nextRecordsUrl"])
	}
}

func TestQueryWithSingleBatchSOQLLimitOffsetKeepsExactTotalSize(t *testing.T) {
	query := &windowQueryCapture{
		result: &contract.QueryResult{
			TotalSize: 63,
			Done:      true,
			Records: []contract.Record{
				{"Id": "00Q54"},
				{"Id": "00Q55"},
				{"Id": "00Q56"},
				{"Id": "00Q57"},
				{"Id": "00Q58"},
				{"Id": "00Q59"},
				{"Id": "00Q60"},
				{"Id": "00Q61"},
				{"Id": "00Q62"},
				{"Id": "00Q63"},
			},
		},
	}

	resp, err := QueryNeutralHandler(context.Background(), &dialect.Request{
		Version: "v63.0",
		Query: map[string][]string{
			"q": {"SELECT Id FROM Lead ORDER BY CreatedDate DESC LIMIT 10 OFFSET 53"},
		},
		User: &models.UserSession{ID: "005-reader"},
	}, dialect.Deps{Contracts: contract.Deps{Query: query}})
	if err != nil {
		t.Fatalf("QueryNeutralHandler error = %v", err)
	}
	if resp.Status != 200 {
		t.Fatalf("status = %d, want 200; body=%#v", resp.Status, resp.Body)
	}
	if query.spec.SkipTotalSize {
		t.Fatal("SkipTotalSize = true, want false for SOQL LIMIT/OFFSET window")
	}
	if query.spec.Limit != 10 || query.spec.Offset != 53 {
		t.Fatalf("query window = limit %d offset %d, want 10/53", query.spec.Limit, query.spec.Offset)
	}
	body := queryResponseBody(t, resp)
	if body["totalSize"] != 10 {
		t.Fatalf("totalSize = %#v, want 10", body["totalSize"])
	}
	if body["done"] != true {
		t.Fatalf("done = %#v, want true because the SOQL LIMIT/OFFSET window is exhausted", body["done"])
	}
	records, ok := body["records"].([]interface{})
	if !ok {
		t.Fatalf("records = %T %#v, want []interface{}", body["records"], body["records"])
	}
	if len(records) != 10 {
		t.Fatalf("records len = %d, want 10", len(records))
	}
	if _, ok := body["nextRecordsUrl"]; ok {
		t.Fatalf("nextRecordsUrl present for exhausted SOQL LIMIT/OFFSET window: %#v", body["nextRecordsUrl"])
	}
}

func TestQueryWithoutSOQLLimitKeepsExactTotalSize(t *testing.T) {
	query := &windowQueryCapture{
		result: &contract.QueryResult{
			TotalSize: 3,
			Done:      true,
			Records: []contract.Record{
				{"Id": "00Q1"},
			},
		},
	}

	resp, err := QueryNeutralHandler(context.Background(), &dialect.Request{
		Version: "v63.0",
		Query: map[string][]string{
			"q": {"SELECT Id FROM Lead ORDER BY CreatedDate DESC"},
		},
		User: &models.UserSession{ID: "005-reader"},
	}, dialect.Deps{Contracts: contract.Deps{Query: query}})
	if err != nil {
		t.Fatalf("QueryNeutralHandler error = %v", err)
	}
	if resp.Status != 200 {
		t.Fatalf("status = %d, want 200; body=%#v", resp.Status, resp.Body)
	}
	if query.spec.SkipTotalSize {
		t.Fatal("SkipTotalSize = true, want false for non-windowed SOQL query")
	}
	if query.spec.Limit != queryDefaultBatchSize {
		t.Fatalf("query limit = %d, want default batch size %d", query.spec.Limit, queryDefaultBatchSize)
	}
	body := queryResponseBody(t, resp)
	if body["totalSize"] != 3 {
		t.Fatalf("totalSize = %#v, want exact total 3", body["totalSize"])
	}
}

func queryResponseBody(t *testing.T, resp *dialect.Response) map[string]any {
	t.Helper()
	body, ok := resp.Body.(map[string]any)
	if !ok {
		t.Fatalf("body = %T %#v, want map[string]any", resp.Body, resp.Body)
	}
	return body
}

type windowQueryCapture struct {
	spec   queryspec.QuerySpec
	result *contract.QueryResult
}

func (q *windowQueryCapture) Query(_ context.Context, spec queryspec.QuerySpec, _ *models.UserSession) (*contract.QueryResult, error) {
	q.spec = spec
	return q.result, nil
}

func (q *windowQueryCapture) SearchWithSpec(context.Context, queryspec.SearchSpec, *models.UserSession) ([]contract.Record, error) {
	return nil, errors.New("unexpected SearchWithSpec call")
}

func (q *windowQueryCapture) GlobalSearchWithSpec(context.Context, queryspec.GlobalSearchSpec, *models.UserSession) ([]contract.SearchResult, error) {
	return nil, errors.New("unexpected GlobalSearchWithSpec call")
}

func (q *windowQueryCapture) QueryHistory(context.Context, contract.HistoryQueryRequest, *models.UserSession) (*contract.HistoryQueryResult, error) {
	return nil, errors.New("unexpected QueryHistory call")
}
