package com.kt.distribution.adapter;

import com.kt.distribution.client.NaverBlogClient;
import com.kt.distribution.dto.ChannelDistributionResult;
import com.kt.distribution.dto.ChannelType;
import com.kt.distribution.dto.DistributionRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * Naver Blog Adapter
 * Naver Blog 포스팅 (Playwright 기반)
 *
 * @author Backend Developer
 * @since 2025-10-29
 */
@Slf4j
@Component
@RequiredArgsConstructor
@ConditionalOnProperty(name = "naver.blog.enabled", havingValue = "true", matchIfMissing = false)
public class NaverAdapter extends AbstractChannelAdapter {

    private final NaverBlogClient naverBlogClient;

    @Override
    public ChannelType getChannelType() {
        return ChannelType.NAVER;
    }

    @Override
    protected ChannelDistributionResult executeDistribution(DistributionRequest request) {
        log.debug("Posting to Naver Blog: eventId={}, title={}",
                request.getEventId(), request.getTitle());

        try {
            // 네이버 블로그에 포스팅
            String postUrl = naverBlogClient.postToBlog(request);
            String distributionId = "NAVER-" + UUID.randomUUID().toString();

            log.info("Naver blog post created successfully: eventId={}, postUrl={}",
                    request.getEventId(), postUrl);

            return ChannelDistributionResult.builder()
                    .channel(ChannelType.NAVER)
                    .success(true)
                    .distributionId(distributionId)
                    .postUrl(postUrl)
                    .estimatedReach(2000) // 블로그 방문자 수 기반
                    .build();

        } catch (Exception e) {
            log.error("Failed to post to Naver blog: eventId={}, error={}",
                    request.getEventId(), e.getMessage(), e);

            return ChannelDistributionResult.builder()
                    .channel(ChannelType.NAVER)
                    .success(false)
                    .errorMessage("Naver blog posting failed: " + e.getMessage())
                    .estimatedReach(0)
                    .build();
        }
    }
}
