package e2e

import (
	"context"
	"fmt"
	"testing"

	"code.justin.tv/eventbus/controlplane/internal/db"
	"code.justin.tv/eventbus/controlplane/internal/db/postgres"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
)

type IAMRolesE2ETest struct {
	suite.Suite

	service *db.Service

	dbConn *postgres.PostgresDB
}

func (suite *IAMRolesE2ETest) SetupTest() {
	ctx := context.Background()

	conn, err := newLocalDB()
	suite.NoError(err, "no db connection created in IAMRolesE2ETest")
	suite.dbConn = conn

	suite.service = createService("S2", "wow-team", "wow service", "456")
	serviceID, err := conn.ServiceCreate(ctx, suite.service)
	suite.service.ID = serviceID
	suite.NoError(err)
}

func (suite *IAMRolesE2ETest) TearDownTest() {
	writer := suite.dbConn.WriterConn()

	_, err := writer.Exec(fmt.Sprintf("DELETE FROM %s;", postgres.IAMRolesTableName))
	suite.NoError(err)
	_, err = writer.Exec(fmt.Sprintf("DELETE FROM %s;", postgres.ServicesTableName))
	suite.NoError(err)

	err = suite.dbConn.Close()
	suite.NoError(err)
}

func (suite *IAMRolesE2ETest) TestIAMRolesE2E() {
	t := suite.T()
	ctx := context.Background()

	t.Run("IAMRoleCreate", func(t *testing.T) {
		iamRole := &db.IAMRole{
			ARN:                  "my-arn",
			Label:                "my-label",
			CloudformationStatus: "my-cfn-status",
			ServiceID:            suite.service.ID,
			KMSGrantID:           "123456",
		}

		_, err := suite.dbConn.IAMRoleCreate(ctx, iamRole)
		assert.NoError(t, err)

		fetchedIAMRole, err := suite.dbConn.IAMRoleByARN(ctx, "my-arn")
		assert.NoError(t, err)
		assert.Equal(t, "my-arn", fetchedIAMRole.ARN)
		assert.Equal(t, "my-label", fetchedIAMRole.Label)
		assert.Equal(t, "123456", fetchedIAMRole.KMSGrantID)
	})
}

func TestIAMRolesE2E(t *testing.T) {
	suite.Run(t, &IAMRolesE2ETest{})
}
