package com.saas.tenant.service;

import com.saas.admin.entity.User;
import com.saas.admin.repository.UserRepository;

import com.saas.shared.enums.UserType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Service for syncing tenant users to saas_db
 * 
 * When a tenant user logs in for the first time, this service syncs them
 * to the central saas_db with subscription mapping
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserSyncService {

    private final UserRepository userRepository;

    /**
     * Sync a tenant user to saas_db on first login
     * 
     * @param email     User email
     * @param firstName User first name
     * @param lastName  User last name
     * @param tenantId  Tenant ID/schema name
     */
    @Transactional
    public void syncTenantUserToSaasDb(String email, String firstName, String lastName, String tenantId) {
        log.info("🔄 Syncing tenant user to saas_db: {} (tenant: {})", email, tenantId);

        // First, check if user exists in saas_db
        if (userRepository.findByEmail(email).isPresent()) {
            log.info("✅ User already exists in saas_db: {}", email);
            return;
        }

        // Create user in saas_db
        User saasDUser = new User();
        saasDUser.setEmail(email);
        saasDUser.setFirstName(firstName);
        saasDUser.setLastName(lastName);
        saasDUser.setUserType(UserType.TENANT_USER);
        saasDUser.setStatus("ACTIVE");
        saasDUser.setRole("TENANT_ADMIN"); // Default role for synced users
        saasDUser.setTenantId(tenantId);

        // Save to saas_db (context should be in saas_db during this operation)
        userRepository.save(saasDUser);
        log.info("✅ User synced successfully to saas_db: {}", email);
    }

    /**
     * Check if user needs to be synced to saas_db
     */
    public boolean needsSync(String email) {
        return userRepository.findByEmail(email).isEmpty();
    }
}
