package location

import (
	"context"
	"database/sql"
	"github.com/DATA-DOG/go-sqlmock"
	"github.com/UpmeshLTD/urus-aio/infrastructure/db/entities"
	"github.com/UpmeshLTD/urus-aio/mdm/db/gormdb"
	"github.com/magiconair/properties/assert"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"testing"
)

type LocationRepositoryTestSuite struct {
	suite.Suite
	repository Repository
	db         *gorm.DB
	mock       sqlmock.Sqlmock
}

func (s *LocationRepositoryTestSuite) SetupSuite() {
	var (
		db            *sql.DB
		err           error
		gormDBContext gormdb.GormDB
	)

	db, s.mock, err = sqlmock.New()
	require.NoError(s.T(), err)

	dialector := postgres.New(postgres.Config{
		DSN:                  "sqlmock_db_0",
		DriverName:           "postgres",
		Conn:                 db,
		PreferSimpleProtocol: true,
	})

	s.db, err = gorm.Open(dialector, &gorm.Config{})
	require.NoError(s.T(), err)

	gormDBContext, err = gormdb.Wrap(s.db)
	require.NoError(s.T(), err)

	s.repository = NewRepository(gormDBContext)
}

func (s *LocationRepositoryTestSuite) Test_GetCountryByID_Successfully() {
	var (
		result *entities.Country
		err    error
	)

	expectedCountry := entities.Country{
		BaseEntity: entities.BaseEntity{
			ID: entities.IDFromInt64(1),
		},
		InternationalName: "Singapore",
		LocalizedName:     "Singapura",
		Code:              "SG",
	}

	s.mock.ExpectQuery(`SELECT (.+) FROM "countries"`).
		WillReturnRows(sqlmock.NewRows([]string{"id", "international_name", "localized_name", "code"}).
			AddRow(expectedCountry.ID.ID, expectedCountry.InternationalName, expectedCountry.LocalizedName, expectedCountry.Code))

	result, err = s.repository.GetCountryByID(context.TODO(), expectedCountry.ID.ID)
	require.NoError(s.T(), err)
	assert.Equal(s.T(), expectedCountry.ID, result.ID, "they should be equal")
}

func (s *LocationRepositoryTestSuite) AfterTest(_, _ string) {
	require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
	suite.Run(t, new(LocationRepositoryTestSuite))
}
