package com.ankurm.mapstruct.mapper;

import com.ankurm.mapstruct.dto.CustomerDto;
import com.ankurm.mapstruct.dto.CustomerPatch;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;

/**
 * The way to "update" an immutable record: build a new one from the old one plus the patch.
 * Two source parameters; "." copies every component of {@code current}, then the explicit lines override. Every component
 * that BOTH records have (address, roles, email, nickname) needs an explicit line, or MapStruct reports
 * "Several possible source properties".
 * Save it as RecordPatchMapper.java next to the mappers in the companion module and make the interface public
 * (it is package-private here only so the download can carry the mapstruct- prefix). Needs CustomerDto and CustomerPatch.
 */
@Mapper(componentModel = "spring")
interface RecordPatchMapper {

    @Mapping(target = ".", source = "current")
    @Mapping(target = "email", expression = "java(patch.email() != null ? patch.email() : current.email())")
    @Mapping(target = "nickname", expression = "java(patch.nickname() != null ? patch.nickname() : current.nickname())")
    @Mapping(target = "address", expression = "java(patch.address() != null ? patch.address() : current.address())")
    @Mapping(target = "roles", expression = "java(patch.roles() != null ? patch.roles() : current.roles())")
    CustomerDto apply(CustomerDto current, CustomerPatch patch);
}
