<?php

namespace App\Services\Handlers;

use CodeIgniter\CLI\CLI;
use App\Services\ParameterMapper\TypeSParameterMapper;
use App\Models\Entities\ReceiptModel;
use App\Models\Entities\ResultModel;
use App\Models\Entities\NaverRawStagingModel;
use Exception;

/**
 * Type S 핸들러
 * 현장확인 매물 (A01) 데이터 처리
 */
class TypeSHandler
{
    private $receiptModel;
    private $resultModel;
    private $stagingModel;
    private $db;
    private $parameterMapper;
    private $naverClient;
    
    public function __construct()
    {
        $this->db = \Config\Database::connect();
        $this->receiptModel = new ReceiptModel();
        $this->resultModel = new ResultModel();
        $this->stagingModel = new NaverRawStagingModel();
        $this->parameterMapper = new TypeSParameterMapper();
        $this->naverClient = new \App\Libraries\NaverApiClient();
        helper('log');
    }
    
    /**
     * Type S 메인 처리 로직
     */
    public function handle(string $articleNumber, array $rawData, array $payload): int
    {
        CLI::write(CLI::color('🟢 Type S 처리 시작 :: ' . $articleNumber, 'green'));
        
        $this->db->transBegin();
        
        try {
            // 1. Receipt 데이터 저장
            $receiptData = $this->parameterMapper->mapReceipt($articleNumber, $rawData, $payload);
            if (!$this->receiptModel->insert($receiptData)) {
                throw new Exception("Receipt Insert 실패: " . json_encode($this->receiptModel->errors()));
            }
            $rcptSq = $this->receiptModel->getInsertID();
            CLI::write(CLI::color("✅ Receipt 저장 성공 (ID: $rcptSq)", 'blue'));
            
            // 2. Result 데이터 저장
            $resultData = $this->parameterMapper->mapResult($rcptSq, $rawData);
            if (!$this->resultModel->insert($resultData)) {
                throw new Exception("Result Insert 실패");
            }
            CLI::write(CLI::color('✅ Result 저장 성공', 'blue'));
            
            // 3. 트랜잭션 커밋
            $this->db->transComplete();
            if ($this->db->transStatus() === false) {
                write_custom_log("Type S DB 트랜잭션 최종 실패", 'ERROR', 'service');
                throw new Exception("Type S DB 트랜잭션 최종 실패");
            }
            
            // 4. 로그 기록
            write_custom_log("Type S 처리 성공 | Atcl: $articleNumber | Rcpt_sq: $rcptSq", 'INFO', 'service');
            write_custom_log("Receipt Insert SQL: " . (string)$this->receiptModel->getLastQuery(), 'INFO', 'service');
            write_custom_log("Result Insert SQL: " . (string)$this->resultModel->getLastQuery(), 'INFO', 'service');
            
            // 5. 네이버 예약 정보 동기화 (비동기)
            try {
                $syncResult = $this->naverClient->submitSyncResult($rawData['reserveNo'] ?? '');
                write_custom_log("Naver Sync Result Response: " . json_encode($syncResult), 'INFO', 'service');
            } catch (Exception $e) {
                write_custom_log("Naver Sync 실패 (계속 진행): " . $e->getMessage(), 'WARN', 'service');
            }
            
            return $rcptSq;
            
        } catch (Exception $e) {
            $this->db->transRollback();
            write_custom_log("Type S 처리 실패: " . $e->getMessage(), 'ERROR', 'service');
            throw $e;
        }
    }
}
