package broker

import (
	"local/storage"
	"local/truckstop/config"
	"local/truckstop/logtr"
	"os"
	"path"
	"testing"

	"golang.org/x/time/rate"
)

func TestFastExactReal(t *testing.T) {
	if os.Getenv("INTEGRATION_FAST_EXACT") == "" {
		t.Skip("$INTEGRATION_FAST_EXACT not set")
	}
	os.Setenv("CONFIG", "../config.json")
	if err := config.Refresh(nil); err != nil {
		t.Fatal(err)
	}
	conf := config.Get()
	conf.Storage = []string{"files", path.Join(t.TempDir(), "storage")}
	os.Setenv("CONFIG", path.Join(t.TempDir(), "config.json"))
	config.Set(*conf)
	if err := config.Refresh(nil); err != nil {
		t.Fatal(err)
	}
	states := []config.State{
		config.State("NC"),
	}

	fe := NewFastExact()
	if err := fe.login(); err != nil {
		t.Fatal(err)
	}
	jobs, err := fe.searchStates(states)
	if err != nil {
		t.Fatal(err)
	}

	t.Logf("%d", len(jobs))
	for i := range jobs {
		t.Logf("[%d] %+v", i, jobs[i])
	}
}

func TestFastExactLogin(t *testing.T) {
	logtr.SetLevel(logtr.SOS)
	limiter = rate.NewLimiter(rate.Limit(60.0), 1)
	fe := NewFastExact().WithMock()
	_ = fe
	db := storage.NewMap()
	if err := fe._login("u", "p", db); err != nil {
		t.Fatal(err)
	}
}

func TestFastExactSearchStates(t *testing.T) {
	logtr.SetLevel(logtr.SOS)
	limiter = rate.NewLimiter(rate.Limit(60.0), 1)
	fe := NewFastExact().WithMock()
	_ = fe
	db := storage.NewMap()
	_ = db
	if jobs, err := fe.searchStates([]config.State{config.State("NC"), config.State("SC")}); err != nil {
		t.Fatal(err)
	} else if len(jobs) != 9 {
		t.Fatal(len(jobs))
	} else {
		for _, job := range jobs {
			if job.ID == "" {
				t.Error(job)
			} else if job.Miles == 0 {
				t.Error(job)
			} else if job.URI == "" {
				t.Error(job)
			} else if job.Meta == "" {
				t.Error(job)
			} else if job.Weight == 0 {
				t.Error(job)
			} else if job.Pickup.Date.IsZero() {
				t.Error(job)
			} else if job.Pickup.Date != job.Dropoff.Date {
				t.Error(job)
			} else if job.Dropoff.State == "" {
				t.Error(job)
			} else if job.Dropoff.City == "" {
				t.Error(job)
			} else if job.Pickup.State == "" {
				t.Error(job)
			} else if job.Pickup.City == "" {
				t.Error(job)
			}
		}
	}
}
