package user

import (
	"context"
	"testing"

	"tercul/internal/app/authz"
	"tercul/internal/domain"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/suite"
	"gorm.io/gorm"
)

// mockUserProfileRepository is a mock implementation of the UserProfileRepository
type mockUserProfileRepository struct {
	mock.Mock
}

func (m *mockUserProfileRepository) GetByUserID(ctx context.Context, userID uint) (*domain.UserProfile, error) {
	args := m.Called(ctx, userID)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) Create(ctx context.Context, entity *domain.UserProfile) error {
	args := m.Called(ctx, entity)
	return args.Error(0)
}

func (m *mockUserProfileRepository) CreateInTx(ctx context.Context, tx *gorm.DB, entity *domain.UserProfile) error {
	args := m.Called(ctx, tx, entity)
	return args.Error(0)
}

func (m *mockUserProfileRepository) GetByID(ctx context.Context, id uint) (*domain.UserProfile, error) {
	args := m.Called(ctx, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) GetByIDWithOptions(ctx context.Context, id uint, options *domain.QueryOptions) (*domain.UserProfile, error) {
	args := m.Called(ctx, id, options)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) Update(ctx context.Context, entity *domain.UserProfile) error {
	args := m.Called(ctx, entity)
	return args.Error(0)
}

func (m *mockUserProfileRepository) UpdateInTx(ctx context.Context, tx *gorm.DB, entity *domain.UserProfile) error {
	args := m.Called(ctx, tx, entity)
	return args.Error(0)
}

func (m *mockUserProfileRepository) Delete(ctx context.Context, id uint) error {
	args := m.Called(ctx, id)
	return args.Error(0)
}

func (m *mockUserProfileRepository) DeleteInTx(ctx context.Context, tx *gorm.DB, id uint) error {
	args := m.Called(ctx, tx, id)
	return args.Error(0)
}

func (m *mockUserProfileRepository) List(ctx context.Context, page, pageSize int) (*domain.PaginatedResult[domain.UserProfile], error) {
	args := m.Called(ctx, page, pageSize)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.PaginatedResult[domain.UserProfile]), args.Error(1)
}

func (m *mockUserProfileRepository) ListWithOptions(ctx context.Context, options *domain.QueryOptions) ([]domain.UserProfile, error) {
	args := m.Called(ctx, options)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).([]domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) ListAll(ctx context.Context) ([]domain.UserProfile, error) {
	args := m.Called(ctx)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).([]domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) Count(ctx context.Context) (int64, error) {
	args := m.Called(ctx)
	return args.Get(0).(int64), args.Error(1)
}

func (m *mockUserProfileRepository) CountWithOptions(ctx context.Context, options *domain.QueryOptions) (int64, error) {
	args := m.Called(ctx, options)
	return args.Get(0).(int64), args.Error(1)
}

func (m *mockUserProfileRepository) FindWithPreload(ctx context.Context, preloads []string, id uint) (*domain.UserProfile, error) {
	args := m.Called(ctx, preloads, id)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) GetAllForSync(ctx context.Context, batchSize, offset int) ([]domain.UserProfile, error) {
	args := m.Called(ctx, batchSize, offset)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).([]domain.UserProfile), args.Error(1)
}

func (m *mockUserProfileRepository) Exists(ctx context.Context, id uint) (bool, error) {
	args := m.Called(ctx, id)
	return args.Bool(0), args.Error(1)
}

func (m *mockUserProfileRepository) BeginTx(ctx context.Context) (*gorm.DB, error) {
	args := m.Called(ctx)
	if args.Get(0) == nil {
		return nil, args.Error(1)
	}
	return args.Get(0).(*gorm.DB), args.Error(1)
}

func (m *mockUserProfileRepository) WithTx(ctx context.Context, fn func(tx *gorm.DB) error) error {
	args := m.Called(ctx, fn)
	return args.Error(0)
}

type UserQueriesSuite struct {
	suite.Suite
	userRepo    *mockUserRepository
	profileRepo *mockUserProfileRepository
	queries     *UserQueries
}

func (s *UserQueriesSuite) SetupTest() {
	s.userRepo = new(mockUserRepository)
	s.profileRepo = new(mockUserProfileRepository)
	s.queries = NewUserQueries(s.userRepo, s.profileRepo)
}

func TestUserQueriesSuite(t *testing.T) {
	suite.Run(t, new(UserQueriesSuite))
}

func (s *UserQueriesSuite) TestUser() {
	// Arrange
	ctx := context.Background()
	testUser := &domain.User{BaseModel: domain.BaseModel{ID: 1}, Username: "testuser"}

	s.userRepo.On("GetByID", ctx, uint(1)).Return(testUser, nil)

	// Act
	user, err := s.queries.User(ctx, 1)

	// Assert
	assert.NoError(s.T(), err)
	assert.NotNil(s.T(), user)
	assert.Equal(s.T(), "testuser", user.Username)
	s.userRepo.AssertExpectations(s.T())
}

func (s *UserQueriesSuite) TestUserByUsername() {
	// Arrange
	ctx := context.Background()
	testUser := &domain.User{BaseModel: domain.BaseModel{ID: 1}, Username: "testuser"}

	s.userRepo.On("FindByUsername", ctx, "testuser").Return(testUser, nil)

	// Act
	user, err := s.queries.UserByUsername(ctx, "testuser")

	// Assert
	assert.NoError(s.T(), err)
	assert.NotNil(s.T(), user)
	assert.Equal(s.T(), uint(1), user.ID)
	s.userRepo.AssertExpectations(s.T())
}

func (s *UserQueriesSuite) TestUserByEmail() {
	// Arrange
	ctx := context.Background()
	testUser := &domain.User{BaseModel: domain.BaseModel{ID: 1}, Email: "test@example.com"}

	s.userRepo.On("FindByEmail", ctx, "test@example.com").Return(testUser, nil)

	// Act
	user, err := s.queries.UserByEmail(ctx, "test@example.com")

	// Assert
	assert.NoError(s.T(), err)
	assert.NotNil(s.T(), user)
	assert.Equal(s.T(), uint(1), user.ID)
	s.userRepo.AssertExpectations(s.T())
}

func (s *UserQueriesSuite) TestUsersByRole() {
	// Arrange
	ctx := context.Background()
	testUsers := []domain.User{
		{BaseModel: domain.BaseModel{ID: 1}, Role: domain.UserRoleAdmin},
	}

	s.userRepo.On("ListByRole", ctx, domain.UserRoleAdmin).Return(testUsers, nil)

	// Act
	users, err := s.queries.UsersByRole(ctx, domain.UserRoleAdmin)

	// Assert
	assert.NoError(s.T(), err)
	assert.Len(s.T(), users, 1)
	s.userRepo.AssertExpectations(s.T())
}

func (s *UserQueriesSuite) TestUsers() {
	// Arrange
	ctx := context.Background()
	testUsers := []domain.User{
		{BaseModel: domain.BaseModel{ID: 1}},
		{BaseModel: domain.BaseModel{ID: 2}},
	}

	s.userRepo.On("ListAll", ctx).Return(testUsers, nil)

	// Act
	users, err := s.queries.Users(ctx)

	// Assert
	assert.NoError(s.T(), err)
	assert.Len(s.T(), users, 2)
	s.userRepo.AssertExpectations(s.T())
}

func (s *UserQueriesSuite) TestUserProfile() {
	// Arrange
	ctx := context.Background()
	testProfile := &domain.UserProfile{BaseModel: domain.BaseModel{ID: 1}, UserID: 1, Website: "https://example.com"}

	s.profileRepo.On("GetByUserID", ctx, uint(1)).Return(testProfile, nil)

	// Act
	profile, err := s.queries.UserProfile(ctx, 1)

	// Assert
	assert.NoError(s.T(), err)
	assert.NotNil(s.T(), profile)
	assert.Equal(s.T(), "https://example.com", profile.Website)
	s.profileRepo.AssertExpectations(s.T())
}

func TestNewService(t *testing.T) {
	// Arrange
	userRepo := new(mockUserRepository)
	profileRepo := new(mockUserProfileRepository)
	authzSvc := authz.NewService(nil, nil, nil, nil)

	// Act
	service := NewService(userRepo, authzSvc, profileRepo)

	// Assert
	assert.NotNil(t, service)
	assert.NotNil(t, service.Commands)
	assert.NotNil(t, service.Queries)
}