package services

import (
	"context"
	"database/sql"
	"testing"

	"quyun/v2/app/commands/testx"
	"quyun/v2/database"
	"quyun/v2/database/models"
	"quyun/v2/pkg/consts"

	. "github.com/smartystreets/goconvey/convey"
	"github.com/stretchr/testify/suite"
	"go.ipao.vip/atom/contracts"
	"go.uber.org/dig"
)

type TenantTestSuiteInjectParams struct {
	dig.In

	DB       *sql.DB
	Initials []contracts.Initial `group:"initials"`
}

type TenantTestSuite struct {
	suite.Suite
	TenantTestSuiteInjectParams
}

func Test_Tenant(t *testing.T) {
	providers := testx.Default().With(Provide)

	testx.Serve(providers, t, func(p TenantTestSuiteInjectParams) {
		suite.Run(t, &TenantTestSuite{TenantTestSuiteInjectParams: p})
	})
}

func (s *TenantTestSuite) Test_Follow() {
	Convey("Follow Flow", s.T(), func() {
		ctx := s.T().Context()
		tenantID := int64(0)
		database.Truncate(ctx, s.DB, models.TableNameTenant, models.TableNameTenantUser, models.TableNameUser)

		// User
		u := &models.User{Username: "user_f", Phone: "13900000004"}
		models.UserQuery.WithContext(ctx).Create(u)
		ctx = context.WithValue(ctx, consts.CtxKeyUser, u.ID)

		// Tenant
		t := &models.Tenant{Name: "Tenant A", Status: consts.TenantStatusVerified}
		models.TenantQuery.WithContext(ctx).Create(t)
		tenantID = t.ID

		Convey("should follow tenant", func() {
			err := Tenant.Follow(ctx, tenantID, u.ID)
			So(err, ShouldBeNil)

			// Verify stats
			profile, err := Tenant.GetPublicProfile(ctx, tenantID, u.ID)
			So(err, ShouldBeNil)
			So(profile.IsFollowing, ShouldBeTrue)
			So(profile.Stats.Followers, ShouldEqual, 1)

			// List Followed
			list, err := Tenant.ListFollowed(ctx, tenantID, u.ID)
			So(err, ShouldBeNil)
			So(len(list), ShouldEqual, 1)
			So(list[0].Name, ShouldEqual, "Tenant A")

			// Unfollow
			err = Tenant.Unfollow(ctx, tenantID, u.ID)
			So(err, ShouldBeNil)

			// Verify
			profile, err = Tenant.GetPublicProfile(ctx, tenantID, u.ID)
			So(err, ShouldBeNil)
			So(profile.IsFollowing, ShouldBeFalse)
			So(profile.Stats.Followers, ShouldEqual, 0)
		})
	})
}
