package e2e

import (
	"database/sql"
	"fmt"
	"os"

	"code.justin.tv/eventbus/controlplane/internal/db"
	"code.justin.tv/eventbus/controlplane/internal/db/postgres"
	"code.justin.tv/eventbus/controlplane/internal/uuid"
)

func newLocalDB() (*postgres.PostgresDB, error) {
	return postgres.New(postgres.Config{
		Reader: postgres.ConnectionConfig{
			Username: os.Getenv("POSTGRES_READER_USER"),
			Password: os.Getenv("POSTGRES_READER_PASSWORD"),
			Hostname: os.Getenv("POSTGRES_READER_HOST"),
			Dbname:   os.Getenv("POSTGRES_DB"),
			Sslmode:  "disable",
		},
		Writer: postgres.ConnectionConfig{
			Username: os.Getenv("POSTGRES_WRITER_USER"),
			Password: os.Getenv("POSTGRES_WRITER_PASSWORD"),
			Hostname: os.Getenv("POSTGRES_WRITER_HOST"),
			Dbname:   os.Getenv("POSTGRES_DB"),
			Sslmode:  "disable",
		},
	})
}

func createPublication(eventStreamID int, accountID, iamRoleID *int) *db.Publication {
	p := &db.Publication{
		EventStreamID: eventStreamID,
	}
	if accountID != nil {
		p.AccountID = sql.NullInt64{
			Int64: int64(*accountID),
			Valid: true,
		}
	}
	if iamRoleID != nil {
		p.IAMRoleID = sql.NullInt64{
			Int64: int64(*iamRoleID),
			Valid: true,
		}
	}
	return p
}

func createService(name, ldapGroup, desc, scID string) *db.Service {
	return &db.Service{
		Name:             name,
		LDAPGroup:        ldapGroup,
		Description:      desc,
		ServiceCatalogID: scID,
	}
}

func createIAMRole(awsAccountID, label string, serviceID int) *db.IAMRole {
	return &db.IAMRole{
		ARN:       fmt.Sprintf("arn:aws:iam::%s:role/???-%s", awsAccountID, uuid.NewUUIDMust()),
		Label:     label,
		ServiceID: serviceID,
	}
}
