package com.gcsc.connection.tenant.service;

import com.gcsc.connection.common.exception.BusinessException;
import com.gcsc.connection.common.exception.ErrorCode;
import com.gcsc.connection.tenant.dto.CreateTenantRequest;
import com.gcsc.connection.tenant.dto.TenantResponse;
import com.gcsc.connection.tenant.dto.UpdateTenantRequest;
import com.gcsc.connection.tenant.entity.SnpTenant;
import com.gcsc.connection.tenant.repository.SnpTenantRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class TenantService {

    private final SnpTenantRepository snpTenantRepository;

    /**
     * 전체 테넌트 목록 조회
     */
    @Transactional(readOnly = true)
    public List<TenantResponse> getTenants() {
        return snpTenantRepository.findAll().stream()
            .map(TenantResponse::from)
            .toList();
    }

    /**
     * 테넌트 생성
     */
    @Transactional
    public TenantResponse createTenant(CreateTenantRequest request) {
        if (snpTenantRepository.existsByTenantCode(request.tenantCode())) {
            throw new BusinessException(ErrorCode.TENANT_CODE_DUPLICATE);
        }

        SnpTenant tenant = SnpTenant.builder()
            .tenantCode(request.tenantCode())
            .tenantName(request.tenantName())
            .description(request.description())
            .build();

        SnpTenant saved = snpTenantRepository.save(tenant);
        log.info("테넌트 생성 완료: {}", saved.getTenantCode());
        return TenantResponse.from(saved);
    }

    /**
     * 테넌트 수정
     */
    @Transactional
    public TenantResponse updateTenant(Long id, UpdateTenantRequest request) {
        SnpTenant tenant = snpTenantRepository.findById(id)
            .orElseThrow(() -> new BusinessException(ErrorCode.TENANT_NOT_FOUND));

        tenant.update(request.tenantName(), request.description(), request.isActive());
        log.info("테넌트 수정 완료: {}", tenant.getTenantCode());
        return TenantResponse.from(tenant);
    }
}
