package graphql_test

import (
	"context"
	"errors"
	"fmt"
	"os"
	"tercul/internal/adapters/graphql"
	"tercul/internal/adapters/graphql/model"
	"tercul/internal/app/auth"
	"tercul/internal/domain"
	platform_auth "tercul/internal/platform/auth"
	"tercul/internal/testutil"
	"testing"

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

type UserMutationTestSuite struct {
	testutil.IntegrationTestSuite
	resolver graphql.MutationResolver
}

func TestUserMutations(t *testing.T) {
	suite.Run(t, new(UserMutationTestSuite))
}

func (s *UserMutationTestSuite) SetupSuite() {
	s.IntegrationTestSuite.SetupSuite(&testutil.TestConfig{
		DBPath: "user_mutations_test.db",
	})
}

func (s *UserMutationTestSuite) TearDownSuite() {
	s.IntegrationTestSuite.TearDownSuite()
	_ = os.Remove("user_mutations_test.db")
}

func (s *UserMutationTestSuite) SetupTest() {
	s.IntegrationTestSuite.SetupTest()
	s.resolver = (&graphql.Resolver{App: s.App}).Mutation()
}

// Helper to create a user for tests
func (s *UserMutationTestSuite) createUser(username, email, password string, role domain.UserRole) *domain.User {
	resp, err := s.App.Auth.Commands.Register(context.Background(), auth.RegisterInput{
		Username: username,
		Email:    email,
		Password: password,
	})
	s.Require().NoError(err)

	user, err := s.App.User.Queries.User(context.Background(), resp.User.ID)
	s.Require().NoError(err)

	if role != user.Role {
		user.Role = role
		err = s.DB.Save(user).Error
		s.Require().NoError(err)
	}
	return user
}

// Helper to create a context with JWT claims
func (s *UserMutationTestSuite) contextWithClaims(user *domain.User) context.Context {
	return testutil.ContextWithClaims(context.Background(), &platform_auth.Claims{
		UserID: user.ID,
		Role:   string(user.Role),
	})
}

func (s *UserMutationTestSuite) TestDeleteUser() {
	s.Run("Success as admin", func() {
		// Arrange
		adminUser := s.createUser("admin_deleter", "admin_deleter@test.com", "password123", domain.UserRoleAdmin)
		userToDelete := s.createUser("user_to_delete", "user_to_delete@test.com", "password123", domain.UserRoleReader)
		ctx := s.contextWithClaims(adminUser)
		userIDToDeleteStr := fmt.Sprintf("%d", userToDelete.ID)

		// Act
		deleted, err := s.resolver.DeleteUser(ctx, userIDToDeleteStr)

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

		// Verify user is deleted from DB
		_, err = s.App.User.Queries.User(context.Background(), userToDelete.ID)
		s.Require().Error(err)
		s.Contains(err.Error(), "entity not found", "Expected user to be not found after deletion")
	})

	s.Run("Success as self", func() {
		// Arrange
		userToDelete := s.createUser("user_to_delete_self", "user_to_delete_self@test.com", "password123", domain.UserRoleReader)
		ctx := s.contextWithClaims(userToDelete)
		userIDToDeleteStr := fmt.Sprintf("%d", userToDelete.ID)

		// Act
		deleted, err := s.resolver.DeleteUser(ctx, userIDToDeleteStr)

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

		// Verify user is deleted from DB
		_, err = s.App.User.Queries.User(context.Background(), userToDelete.ID)
		s.Require().Error(err)
		s.Contains(err.Error(), "entity not found", "Expected user to be not found after deletion")
	})

	s.Run("Forbidden as other user", func() {
		// Arrange
		otherUser := s.createUser("other_user_deleter", "other_user_deleter@test.com", "password123", domain.UserRoleReader)
		userToDelete := s.createUser("user_to_be_kept", "user_to_be_kept@test.com", "password123", domain.UserRoleReader)
		ctx := s.contextWithClaims(otherUser)
		userIDToDeleteStr := fmt.Sprintf("%d", userToDelete.ID)

		// Act
		deleted, err := s.resolver.DeleteUser(ctx, userIDToDeleteStr)

		// Assert
		s.Require().Error(err)
		s.False(deleted)
		s.True(errors.Is(err, domain.ErrForbidden))
	})

	s.Run("Invalid user ID", func() {
		// Arrange
		adminUser := s.createUser("admin_deleter_2", "admin_deleter_2@test.com", "password123", domain.UserRoleAdmin)
		ctx := s.contextWithClaims(adminUser)

		// Act
		deleted, err := s.resolver.DeleteUser(ctx, "invalid-id")

		// Assert
		s.Require().Error(err)
		s.False(deleted)
		s.True(errors.Is(err, domain.ErrValidation))
	})

	s.Run("User not found", func() {
		// Arrange
		adminUser := s.createUser("admin_deleter_3", "admin_deleter_3@test.com", "password123", domain.UserRoleAdmin)
		ctx := s.contextWithClaims(adminUser)
		nonExistentID := "999999"

		// Act
		deleted, err := s.resolver.DeleteUser(ctx, nonExistentID)

		// Assert
		s.Require().Error(err)
		s.False(deleted)
		s.Contains(err.Error(), "entity not found", "Expected entity not found error for non-existent user")
	})
}

func (s *UserMutationTestSuite) TestUpdateProfile() {
	s.Run("Success", func() {
		// Arrange
		user := s.createUser("profile_user", "profile.user@test.com", "password123", domain.UserRoleReader)
		ctx := s.contextWithClaims(user)

		newFirstName := "John"
		newLastName := "Doe"
		newBio := "This is my new bio."
		input := model.UserInput{
			FirstName: &newFirstName,
			LastName:  &newLastName,
			Bio:       &newBio,
		}

		// Act
		updatedUser, err := s.resolver.UpdateProfile(ctx, input)

		// Assert
		s.Require().NoError(err)
		s.Require().NotNil(updatedUser)
		s.Equal(newFirstName, *updatedUser.FirstName)
		s.Equal(newLastName, *updatedUser.LastName)
		s.Equal(newBio, *updatedUser.Bio)

		// Verify in DB
		dbUser, err := s.App.User.Queries.User(context.Background(), user.ID)
		s.Require().NoError(err)
		s.Equal(newFirstName, dbUser.FirstName)
		s.Equal(newLastName, dbUser.LastName)
		s.Equal(newBio, dbUser.Bio)
	})

	s.Run("Unauthenticated user", func() {
		// Arrange
		newFirstName := "Jane"
		input := model.UserInput{FirstName: &newFirstName}

		// Act
		_, err := s.resolver.UpdateProfile(context.Background(), input)

		// Assert
		s.Require().Error(err)
		s.ErrorIs(err, domain.ErrUnauthorized)
	})

	s.Run("Invalid country ID", func() {
		// Arrange
		user := s.createUser("profile_user_invalid", "profile.user.invalid@test.com", "password123", domain.UserRoleReader)
		ctx := s.contextWithClaims(user)
		invalidCountryID := "not-a-number"
		input := model.UserInput{CountryID: &invalidCountryID}

		// Act
		_, err := s.resolver.UpdateProfile(ctx, input)

		// Assert
		s.Require().Error(err)
		s.Contains(err.Error(), "invalid country ID")
	})
}
