package sql_test

import (
	"context"
	"testing"
	"tercul/internal/data/sql"
	"tercul/internal/domain"
	"tercul/internal/platform/config"
	"tercul/internal/testutil"

	"github.com/stretchr/testify/suite"
)

type MonetizationRepositoryTestSuite struct {
	testutil.IntegrationTestSuite
	MonetizationRepo domain.MonetizationRepository
}

func (s *MonetizationRepositoryTestSuite) SetupSuite() {
	s.IntegrationTestSuite.SetupSuite(testutil.DefaultTestConfig())
	cfg, err := config.LoadConfig()
	s.Require().NoError(err)
	s.MonetizationRepo = sql.NewMonetizationRepository(s.DB, cfg)
}

func (s *MonetizationRepositoryTestSuite) SetupTest() {
	s.IntegrationTestSuite.SetupTest()
	s.DB.Exec("DELETE FROM work_monetizations")
	s.DB.Exec("DELETE FROM monetizations")
	s.DB.Exec("DELETE FROM works")
}

func (s *MonetizationRepositoryTestSuite) TestAddMonetizationToWork() {
	s.Run("should add a monetization to a work", func() {
		// Arrange
		work := s.CreateTestWork(s.AdminCtx, "Test Work", "en", "Test content")
		monetization := &domain.Monetization{Amount: 10.0}
		s.Require().NoError(s.DB.Create(monetization).Error)

		// Act
		err := s.MonetizationRepo.AddMonetizationToWork(context.Background(), work.ID, monetization.ID)

		// Assert
		s.Require().NoError(err)

		// Verify that the association was created in the database
		var foundWork domain.Work
		err = s.DB.Preload("Monetizations").First(&foundWork, work.ID).Error
		s.Require().NoError(err)
		s.Require().Len(foundWork.Monetizations, 1)
		s.Equal(monetization.ID, foundWork.Monetizations[0].ID)
	})
}

func TestMonetizationRepository(t *testing.T) {
	suite.Run(t, new(MonetizationRepositoryTestSuite))
}