<?php

namespace App\Services\ParameterMapper;

/**
 * Type V2 파라미터 매퍼
 * 일반/서류/비공동 매물 데이터를 V2 테이블용 파라미터로 변환
 */
class TypeV2ParameterMapper extends BaseParameterMapper
{
    /**
     * V2 검증 요청 파라미터 생성
     */
    public function mapVrfcReq(string $articleNumber, array $rawData, array $payload): array
    {
        $now = db_now();
        $step = $rawData['step'] ?? '00';
        $rdate = date("YmdHis", strtotime($payload['requestDate'] ?? db_now('YmdHis')));
        
        $files = $rawData['files'] ?? [];
        $fileExtracted = $this->extractFilesByType($files);
        
        $reqType = $this->mapRequestType($payload['requestType'] ?? '');
        
        return [
            'reqSeq'                      => '',
            'atcl_no'                     => $articleNumber,
            'step'                        => $step,
            'cpid'                        => $rawData['cpId'] ?? 'naver',
            'cp_atcl_id'                  => $rawData['cpArticleNumber'] ?? '',
            'trade_type'                  => $rawData['tradeTypeCode'] ?? '',
            'realtor_nm'                  => $rawData['realtor']['realtorName'] ?? null,
            'realtor_tel_no'              => $rawData['realtor']['representativeCellphoneNumber'] ?? null,
            'seller_tel_no'               => $rawData['seller']['cellphoneNumber'] ?? null,
            'vrfc_type'                   => $rawData['verificationTypeCode'] ?? 'D',
            'rgbk_confirm'                => ($rawData['isNeedRegisterBookConfirm'] ?? false) ? 'Y' : 'N',
            'req_type'                    => $reqType,
            'rdate'                       => $rdate,
            'cpTelNo'                     => null,
            'stat_cd'                     => '10',
            'insert_user'                 => 0,
            'insert_tm'                   => $now,
            'sync_yn'                     => 'N',
            'rgbk_confirm_owner_nm'       => null,
            'direct_trad_yn'              => ($rawData['seller']['isDirectTrade'] ?? false) ? 'Y' : 'N',
            'confirm_doc_img_url'         => json_encode($fileExtracted['confirmDocImgUrl']),
            'confirm_doc_owner_check_yn'  => ($rawData['seller']['isOwnerCertificationAgree'] ?? false) ? 'Y' : 'N',
            'certRegister'                => json_encode($fileExtracted['certRegister']),
            'referenceFileUrl'            => json_encode($fileExtracted['referenceFileUrl']),
        ];
    }
    
    /**
     * 기사 정보 파라미터 생성
     */
    public function mapArticleInfo(string $articleNumber, array $rawData, array $payload): array
    {
        $address = $rawData['address'] ?? [];
        $space = $rawData['space'] ?? [];
        $price = $rawData['price'] ?? [];
        $floor = $rawData['floor'] ?? [];
        $seller = $rawData['seller'] ?? [];
        $realtor = $rawData['realtor'] ?? [];
        
        $files = $rawData['files'] ?? [];
        $fileExtracted = $this->extractFilesByType($files);
        
        $ownerTypeCode = $this->mapOwnerTypeCode($rawData['ownerTypeCode'] ?? null);
        $ownerCheckYn = ($seller['isOwnerCertificationAgree'] ?? false) ? 'Y' : 'N';
        
        $vrfcTypeSub = $this->mapVrfcTypeSub($rawData['verificationTypeCode'] ?? '', $ownerCheckYn);
        
        return [
            'atcl_no'                       => $articleNumber,
            'cpid'                          => $rawData['cpId'] ?? null,
            'cp_atcl_id'                    => $rawData['cpArticleNumber'] ?? null,
            'rlet_type_cd'                  => $rawData['realEstateTypeCode'] ?? null,
            'trade_type'                    => $rawData['tradeTypeCode'] ?? null,
            'address_code'                  => $address['legalDivision']['sectorNumber'] ?? null,
            'address1'                      => $address['complexName'] ?? null,
            'address2'                      => trim(($address['buildingName'] ?? '') . ' ' . ($address['hoName'] ?? '')),
            'address3'                      => $address['legalDivision']['legalDivisionAddress'] ?? null,
            'sply_spc'                      => $space['supplySpace'] ?? null,
            'excls_spc'                     => $space['exclusiveSpace'] ?? null,
            'tot_spc'                       => $space['totalSpace'] ?? null,
            'grnd_spc'                      => $space['groundSpace'] ?? null,
            'bldg_spc'                      => $space['buildingSpace'] ?? null,
            'deal_amt'                      => $price['dealAmount'] ?? 0,
            'wrrnt_amt'                     => $price['warrantyAmount'] ?? 0,
            'lease_amt'                     => $price['leaseAmount'] ?? 0,
            'isale_amt'                     => $price['preSaleAmount'] ?? 0,
            'prem_amt'                      => $price['premiumAmount'] ?? 0,
            'sise'                          => null,
            'floor'                         => $floor['correspondenceFloorCount'] ?? null,
            'floor2'                        => $floor['totalFloorCount'] ?? null,
            'rdate'                         => date("Y-m-d H:i:s", strtotime($payload['requestDatetime'] ?? 'now')),
            'seller_tel_no'                 => $seller['sellerTelephoneNumber'] ?? null,
            'seller_nm'                     => $seller['sellerName'] ?? null,
            'realtor_nm'                    => $realtor['realtorName'] ?? null,
            'realtor_tel_no'                => $realtor['representativeTelephoneNumber'] ?? null,
            'hscp_no'                       => $address['complexNumber'] ?? null,
            'hscp_nm'                       => $address['complexName'] ?? null,
            'ptp_no'                        => $address['pyeongTypeNumber'] ?? null,
            'ptp_nm'                        => $address['pyeongTypeNumber'] ?? null,
            'charger'                       => null,
            'req_price_yn'                  => 'N',
            'reg_charger'                   => null,
            'dept1_sq'                      => null,
            'dept2_sq'                      => null,
            'reg_dept2_sq'                  => null,
            'reg_dept1_sq'                  => null,
            'dong_ho_chk'                   => ($address['isDongHoCheck'] ?? false) ? 'Y' : 'N',
            'hscplqry_lv'                   => $address['inquiryLevel'] ?? null,
            'ownerNm'                       => $seller['ownerName'] ?? null,
            'ownerTelNo'                    => $seller['ownerTelephoneNumber'] ?? null,
            'chg_trade_type'                => null,
            'chg_address2'                  => null,
            'chg_address3'                  => null,
            'chg_seller_tel'                => null,
            'chg_amt'                       => null,
            'reg_status'                    => null,
            'cupnNo'                        => null,
            'roomSiteAtclRgstCnt'           => null,
            'roomSiteAtclExpsCnt'           => null,
            'redvlp_area_nm'                => $address['redevelopAreaName'] ?? null,
            'biz_stp_desc'                  => $address['bizStepDescription'] ?? null,
            'cert_register'                 => json_encode($fileExtracted['certRegister'], JSON_UNESCAPED_UNICODE),
            'direct_trad_yn'                => ($seller['isDirectTrade'] ?? false) ? 'Y' : 'N',
            'confirm_doc_img_url'           => json_encode($fileExtracted['confirmDocImgUrl'], JSON_UNESCAPED_UNICODE),
            'confirm_doc_owner_check_yn'    => $ownerCheckYn,
            'owner_birth'                   => null,
            'vrfc_type_sub'                 => $vrfcTypeSub,
            'cert_register_save_yn'         => $fileExtracted['cert_register_save_yn'] ?? 'N',
            'confirm_doc_img_url_save_yn'   => $fileExtracted['confirm_doc_img_url_save_yn'] ?? 'N',
            'address4'                      => $address['etcAddress'] ?? null,
            'reference_file_url'            => !empty($fileExtracted['referenceFileUrl']) ? implode('|', $fileExtracted['referenceFileUrl']) : '',
            'reference_file_url_save_yn'    => $fileExtracted['reference_file_url_save_yn'] ?? 'N',
            'registerBookUniqueNo'          => $rawData['verificationReference'] ?? null,
            'relationSellerAndOwner'        => null,
            'ownerTypeCode'                 => $ownerTypeCode,
            'registerBookUniqueNumber'      => null
        ];
    }
    
    /** 
     * 기사 정보 추가 파라미터 생성
     */
    public function mapArticleInfoEtc(string $articleNumber, array $rawData): array
    {
        $address = $rawData['address'] ?? [];
        $realtor = $rawData['realtor'] ?? [];
        
        // 공동주택: 동 정보, 비공동: 지번주소
        $address2b = ($rawData['realEstateTypeCode'] === 'A01') 
            ? $address['buildingName'] 
            : ($address['jibunAddress'] ?? null);
        
        $ownerTypeCode = $this->mapOwnerTypeCode($rawData['ownerTypeCode'] ?? null);
        
        return [
            'atcl_no'                          => $articleNumber,
            'vir_addr_yn'                      => $this->mapYesNo($address['isVirtualAddress'] ?? null),
            'bild_no'                          => null,
            'vrfcMthdTpcd'                     => null,
            'cert_uncnfrm_status'              => null,
            'expsStartYmdt'                    => $rawData['exposureStartDateTime'] ?? null,
            'vrfcAutoPassYn'                   => ($rawData['isAutoVerificationRequested'] ?? false) ? 'Y' : 'N',
            'address2a'                        => $address['liAddress'] ?? null,
            'address2b'                        => $address2b,
            'registerBookUniqueNo'             => null,
            'ownerTypeCode'                    => $ownerTypeCode,
            'orgRepCphNo'                      => null,
            'orgRepTelNo'                      => null,
            'orgRltrNm'                        => null,
            'orgRepNm'                         => null,
            'smsSendTime'                      => null,
            'document_cert_method'             => null,
            'noRgbkVrfcReqYn'                  => $this->mapYesNo($address['isUnregisteredVerificationRequested'] ?? null),
            'areaByBdbkVrfcReqYn'              => $this->mapYesNo($address['isBuildingRegisterAreaCheckRequested'] ?? null),
            'orgAtclNo'                        => null,
            'atclStatCd'                       => null,
            'repNm'                            => $realtor['realtorName'] ?? null,
            'cpName'                           => $rawData['cpId'],
            'document_not_received'            => null,
            'final_failure'                    => null,
        ];
    }
    /**
     * modify_info 파라미터 생성
     */
    public function mapModifyInfo(string $articleNumber, array $rawData, array $payload): array
    {
        $address = $rawData['address'] ?? [];
        $space = $rawData['space'] ?? [];
        $price = $rawData['price'] ?? [];
        $floor = $rawData['floor'] ?? [];
        
        // 공동주택: 동 정보, 비공동: 지번주소
        $address2b = ($rawData['realEstateTypeCode'] === 'A01')
            ? $address['buildingName']
            : ($address['jibunAddress'] ?? null);
        
        return [
            // 'atcl_no'       => $articleNumber,
            'bild_nm'       => $address['buildingName'] ?? null,
            'rm_no'         => $address['hoName'] ?? null,
            'floor'         => $floor['correspondenceFloorCount'] ?? null,
            'floor2'        => $floor['totalFloorCount'] ?? null,
            'address_code'  => $address['legalDivision']['sectorNumber'] ?? null,
            'address2'      => trim(($address['buildingName'] ?? '') . ' ' . ($address['hoName'] ?? '')),
            'address2a'     => $address['liAddress'] ?? null,
            'address2b'     => $address2b,
            'address3'      => $address['legalDivision']['legalDivisionAddress'] ?? null,
            'address4'      => $address['etcAddress'] ?? null,
            'trade_type'    => $rawData['tradeTypeCode'] ?? null,
            'deal_amt'      => $price['dealAmount'] ?? 0,
            'wrrnt_amt'     => $price['warrantyAmount'] ?? 0,
            'lease_amt'     => $price['leaseAmount'] ?? 0,
            'isale_amt'     => $price['preSaleAmount'] ?? 0,
            'prem_amt'      => $price['premiumAmount'] ?? 0,
            'sply_spc'      => $space['supplySpace'] ?? null,
            'excls_spc'     => $space['exclusiveSpace'] ?? null,
            'tot_spc'       => $space['totalSpace'] ?? null,
            'grnd_spc'      => $space['groundSpace'] ?? null,
            'bldg_spc'      => $space['buildingSpace'] ?? null,
            'hscp_no'       => $address['complexNumber'] ?? null,
            'hscp_nm'       => $address['complexName'] ?? null,
            'ptp_no'        => $address['pyeongTypeNumber'] ?? null,
            'ptp_nm'        => $address['pyeongTypeNumber'] ?? null,
            'modify_yn'     => 'N'
        ];
    }
    
    /**
     * 인터페이스 구현
     */
    public function map(string $articleNumber, array $rawData, array $payload): array
    {
        return $this->mapVrfcReq($articleNumber, $rawData, $payload);
    }
    
    /**
     * 요청 타입 매핑
     */
    private function mapRequestType(string $requestType): string
    {
        return match($requestType) {
            'REG' => 'C',
            'MOD' => 'U',
            'CNC' => 'D',
            default => '0',
        };
    }
    
    /**
     * 검증 타입 세부 매핑
     */
    private function mapVrfcTypeSub(string $vrfcType, string $ownerCheckYn): string
    {
        return match($vrfcType) {
            'D' => $ownerCheckYn === 'Y' ? 'D2' : 'D1',
            'N' => 'N2',
            default => $vrfcType . '1',
        };
    }
    
    /**
     * boolean을 Y/N으로 변환
     */
    private function mapYesNo($value): ?string
    {
        if ($value === true) return 'Y';
        if ($value === false) return 'N';
        return null;
    }
}
