<?php

namespace App\Services\ParameterMapper;

use App\Models\Entities\RegionModel;

/**
 * Type S 파라미터 매퍼
 * 현장확인 매물 (A01 등) 데이터를 Receipt 테이블용 파라미터로 변환
 */
class TypeSParameterMapper extends BaseParameterMapper
{
    private $regionModel;
    
    public function __construct()
    {
        $this->regionModel = new RegionModel();
    }
    /**
     * Receipt 테이블용 파라미터 생성
     */
    public function mapReceipt(string $articleNumber, array $rawData, array $payload): array
    {
        $now = db_now();
        $address = $rawData['address'] ?? [];
        $space = $rawData['space'] ?? [];
        $price = $rawData['price'] ?? [];
        $floor = $rawData['floor'] ?? [];
        $seller = $rawData['seller'] ?? [];
        $realtor = $rawData['realtor'] ?? [];
        
        // 평면도 여부 결정
        $groundPlan = in_array($rawData['realEstateTypeCode'] ?? '', ['C01', 'C02']) ? 'N' : 'Y';
        
        // 거래 유형 매핑
        $tradeType = $this->mapTradeType($rawData['tradeType'] ?? null);
        
        return [
            'comp_sq'                => '2',
            'rcpt_rating'            => '3',
            'rcpt_key'               => $articleNumber,
            'rcpt_atclno'            => $articleNumber,
            'rcpt_product'           => $rawData['realEstateTypeCode'] ?? null,
            'rcpt_product_nm'        => $rawData['realEstateType'] ?? null,
            'rcpt_product_info1'     => $rawData['tradeType'] ?? null,
            'rcpt_product_info2'     => $price['dealAmount'] ?? '0',
            'rcpt_product_info4'     => $price['preSaleAmount'] ?? '0',
            'rcpt_product_info5'     => $price['premiumAmount'] ?? '0',
            'rcpt_living_yn'         => ($rawData['site']['isRegistration'] ?? false) ? 'Y' : 'N',
            'rcpt_agent'             => $realtor['realtorName'] ?? null,
            'rcpt_sido'              => $address['legalDivision']['cityNumber'] ?? null,
            'rcpt_gugun'             => $address['legalDivision']['divisionNumber'] ?? null,
            'rcpt_dong'              => $address['legalDivision']['sectorNumber'] ?? null,
            'rcpt_hscp_nm'           => $address['complexName'] ?? null,
            'rcpt_hscp_no'           => $address['complexNumber'] ?? null,
            'rcpt_ptp_nm'            => null,
            'rcpt_ptp_no'            => $address['pyeongTypeNumber'] ?? null,
            'rcpt_dtl_addr'          => trim(
                ($address['legalDivision']['legalDivisionAddress'] ?? '') . 
                ($address['buildingName'] ?? '') . 
                '동 ' . ($address['hoName'] ?? '') . '호'
            ),
            'rcpt_etc_addr'          => $address['hoName'] ?? null,
            'rcpt_floor'             => $floor['correspondenceFloorCount'] ?? null,
            'rcpt_floor2'            => $floor['totalFloorCount'] ?? null,
            'rcpt_exps_type'         => '',
            'rcpt_exp_photo_yn'      => 'Y',
            'rcpt_deal_type'         => $rawData['tradeTypeCode'] ?? null,
            'trade_type'             => $tradeType,
            'ground_plan'            => $groundPlan,
            'excls_spce'             => $space['exclusiveSpace'] ?? null,
            'sply_spc'               => $space['supplySpace'] ?? null,
            'tot_spc'                => $space['totalSpace'] ?? null,
            'grnd_spc'               => $space['groundSpace'] ?? null,
            'bldg_spc'               => $space['buildingSpace'] ?? null,
            'share_spc'              => ($space['supplySpace'] ?? 0) - ($space['exclusiveSpace'] ?? 0),
            'room_cnt'               => $rawData['facilities']['roomCount'] ?? null,
            'cupnNo'                 => $rawData['couponNumber'] ?? null,
            'roomSiteAtclRgstCnt'    => $rawData['site']['monthlyRegisterCount'] ?? null,
            'roomSiteAtclExpsCnt'    => $rawData['site']['monthlyExposureCount'] ?? null,
            'direct_trad_yn'         => ($seller['isDirectTrade'] ?? false) ? 'Y' : 'N',
            'sellr_nm'               => $seller['sellerName'] ?? null,
            'sellr_tel_no'           => $seller['sellerTelephoneNumber'] ?? null,
            'rcpt_ref_addr'          => $address['etcAddress'] ?? null,
            'rcpt_tm'                => $now,
            'rcpt_stat'              => '100000',
            'rcpt_x'                 => $address['longitude'] ?? null,
            'rcpt_y'                 => $address['latitude'] ?? null,
            'agent_id'               => '',
            'agent_nm'               => $realtor['realtorName'] ?? null,
            'agent_head_tel'         => $realtor['representativeCellphoneNumber'] ?? null,
            'rsrv_date'              => $rawData['site']['visitReserveDate'] ?? null,
            'rsrv_tm_ap'             => '00',
            'insert_tm'              => $now,
            'rcpt_cpid'              => $rawData['cpId'] ?? 'naver',
            'isSiteVRVerification'   => ($rawData['site']['isVrVerification'] ?? false) ? 'Y' : 'N',
            'isPromotionApply'       => ($rawData['site']['isVrRepresentativeApply'] ?? false) ? 'Y' : 'N',
        ];
    }
    
    /**
     * Result 테이블용 파라미터 생성
     */
    public function mapResult(int $rcptSq, array $rawData): array
    {
        $now = db_now();

        $address = $rawData['address'] ?? [];
        $sectorNumber = $address['legalDivision']['sectorNumber'] ?? null;
        
        // VR 검증 여부 확인
        $isVrVerification = ($rawData['site']['isVrVerification'] ?? false);
        
        // 1. 지역별 담당자 조회
        $charge = null;
        if ($sectorNumber) {
            $charge = $this->regionModel->getChargeByRegionCd($sectorNumber);
        }
        
        // 2. 기본 담당자 설정 (지역별 담당자가 없으면)
        $deptSq = $charge['dept_sq'] ?? '26';
        $usrSq = $charge['usr_sq'] ?? '1';
        
        // 3. VR 검증인 경우 환경별 담당자로 덮어쓰기
        if ($isVrVerification) {
            if (ENVIRONMENT === 'development') {
                $deptSq = '29';
                $usrSq = '472';
            } else {
                // production
                $deptSq = '33';
                $usrSq = '1993';
            }
        }
        
        return [
            'rcpt_sq'      => $rcptSq,
            'use_yn'       => 'Y',
            'cust_nm'      => '',
            'rsrv_date'    => $rawData['site']['visitReserveDate'] ?? null,
            'rsrv_tm_ap'   => '00',
            'result_cd1'   => '10',
            'result_cd2'   => '1000',
            'result_cd3'   => '100000',
            'insert_tm'    => $now,
            'insert_usr'   => 0,
            'update_tm'    => $now,
            'update_usr'   => 0,
            'dept_sq'      => $deptSq,
            'usr_sq'       => $usrSq,
            'resYn'        => ($rawData['site']['isRegistration'] ?? false) ? 'Y' : 'N',
        ];
    }
    
    /**
     * 인터페이스 구현: 기본 map 메서드
     * (실제로는 mapReceipt와 mapResult를 분리하여 사용)
     */
    public function map(string $articleNumber, array $rawData, array $payload): array
    {
        return $this->mapReceipt($articleNumber, $rawData, $payload);
    }
}
