package com.caliverse.admin.dynamodb.service;

import com.caliverse.admin.domain.request.LandRequest;
import com.caliverse.admin.dynamodb.domain.atrrib.BuildingAttrib;
import com.caliverse.admin.dynamodb.domain.atrrib.LandAttrib;
import com.caliverse.admin.dynamodb.domain.doc.OwnedLandDoc;
import com.caliverse.admin.dynamodb.repository.BuildingRepository;
import com.caliverse.admin.dynamodb.repository.LandRepository;
import com.caliverse.admin.dynamodb.repository.OwnedBuildingRepository;
import com.caliverse.admin.dynamodb.repository.OwnedLandRepository;
import com.caliverse.admin.global.common.annotation.DynamoDBTransaction;
import com.caliverse.admin.global.common.constants.DynamoDBConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@Slf4j
public class DynamodbLandService {
    private final LandRepository landRepository;
    private final OwnedLandRepository ownedLandRepository;
    private final OwnedBuildingRepository ownedBuildingRepository;
    private final BuildingRepository buildingRepository;

    public boolean isLandOwner(Integer landId){
        LandAttrib attrib = landRepository.findLandAttrib(landId);
        if(attrib == null) return false;

        return !attrib.getOwnerUserGuid().isEmpty() && !attrib.getOwnerUserGuid().equals(DynamoDBConstants.EMPTY);
    }

    public LandAttrib getLandInfo(Integer landId){
        return landRepository.findLandAttrib(landId);
    }

    public String getLandOwnerCreateDate(String guid, Integer landId){
        OwnedLandDoc ownedLand = ownedLandRepository.findOwnedLand(guid, landId);
        return ownedLand == null ? "" : ownedLand.getCreatedDateTime();
    }

    @DynamoDBTransaction
    public void ChangesLandOwner(LandRequest landRequest){
        int landId = landRequest.getLandId();
        int buildingId = landRequest.getBuildingId();
        String guid = landRequest.getUserGuid();

        LandAttrib landAttrib = landRepository.findLandAttrib(landId);
        if(landAttrib == null){
            landRepository.insertLand(landRequest);
            ownedLandRepository.insert(guid, landId);
        }else{
            ownedLandRepository.delete(landAttrib.getOwnerUserGuid(), landId);
            landRepository.updateLand(landRequest);
            ownedLandRepository.insert(guid, landId);
        }

        BuildingAttrib buildingAttrib = buildingRepository.findBuildingAttrib(buildingId);
        if(buildingAttrib == null){
            buildingRepository.insertBuilding(landRequest);
            ownedBuildingRepository.insert(guid, landId);
        }else{
            ownedBuildingRepository.delete(buildingAttrib.getOwnerUserGuid(), landId);
            buildingRepository.updateBuilding(landRequest);
            ownedBuildingRepository.insert(guid, landId);
        }
    }
}
