<?php

namespace App\Services;

use CodeIgniter\CLI\CLI;
use App\Libraries\NaverApiClient;
use App\Models\Entities\NaverRawStagingModel;
use App\Services\Handlers\TypeSHandler;
use App\Services\Handlers\TypeV2Handler;
use Exception;

/**
 * 네이버 부동산 매물 처리 서비스
 * 
 * 네이버 API 응답을 받아서 타입별 처리 로직으로 위임하는 오케스트레이터 역할
 * - Type S, S_VR: 현장확인 (A01)
 * - Type V2: 일반/서류/비공동 (D04, F01 등)
 */
class NaverService
{
    private $db;
    private $naverClient;
    private $rawStagingModel;
    private $typeSHandler;
    private $typeV2Handler;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
        $this->naverClient = new NaverApiClient();
        $this->rawStagingModel = new NaverRawStagingModel();
        $this->typeSHandler = new TypeSHandler();
        $this->typeV2Handler = new TypeV2Handler();
        helper('log');
    }

    /**
     * 메인 프로세스: 네이버 API 호출 및 타입별 처리
     * 
     * @param array $payload 요청 페이로드 (articleNumber, requestType 등)
     * @return int 처리된 ID (rcpt_sq 또는 vr_sq)
     * @throws Exception
     */
    public function processArticle(array $payload): int
    {
        $articleNumber = $payload['articleNumber'];
        $requestType = $payload['requestType'] ?? '';

        CLI::write(CLI::color('🟢 getArticleInfo Start :: ' . $articleNumber, 'green'));
        
        try {
            // 1. 네이버 API 호출
            $response = $this->naverClient->getArticleInfo($articleNumber);
            if (!$response || $response['code'] !== 'success') {
                throw new Exception("네이버 API 응답 에러: $articleNumber");
            }

            $rawData = $response['data'];
            $vType = $rawData['verificationTypeCode'] ?? '';

            // 2. 원본 데이터 Staging 저장
            $insertResult = $this->rawStagingModel->insert([
                'atcl_no'           => $articleNumber,
                'verification_type' => $vType,
                'request_type'      => $requestType,
                'raw_json'          => $rawData
            ]);
            
            if (!$insertResult) {
                $dbError = $this->db->error();
                write_custom_log("naver_raw_staging Insert 실패 | Atcl: $articleNumber | Error: " . json_encode($dbError), 'ERROR', 'service');
                throw new Exception("naver_raw_staging 저장 실패: " . json_encode($dbError));
            }
            
            CLI::write(CLI::color('🟢 임시테이블 저장 완료', 'green'));

            // 3. 타입별 분기 처리
            CLI::write(CLI::color("🔵 검증타입 확인: vType = $vType", 'cyan'));
            write_custom_log("타입별 분기 | Atcl: $articleNumber | vType: $vType | requestType: $requestType", 'INFO', 'service');
            
            if ($vType === 'S' || $vType === 'S_VR') {
                CLI::write(CLI::color('🟢 Type S Handler 호출', 'green'));
                return $this->typeSHandler->handle($articleNumber, $rawData, $payload);
            } else {
                CLI::write(CLI::color('🟢 Type V2 Handler 호출', 'green'));
                $result = $this->typeV2Handler->handle($articleNumber, $rawData, $payload);
                write_custom_log("TypeV2Handler 완료 | Atcl: $articleNumber | Result: $result", 'INFO', 'service');
                return $result;
            }
            
        } catch (Exception $e) {
            write_custom_log("processArticle 실패: " . $e->getMessage(), 'ERROR', 'service');
            throw $e;
        }
    }
}

