/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package org.grails.datastore.gorm.mongo

import grails.gorm.services.Service
import grails.gorm.services.Where
import grails.persistence.Entity

import jakarta.persistence.Embeddable
import org.apache.grails.data.mongo.core.GrailsDataMongoTckManager
import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec

class EmbeddedWhereClauseSpec extends GrailsDataTckSpec<GrailsDataMongoTckManager> {
    void setupSpec() {
        manager.domainClasses.addAll([PersonAttribute])
    }

    void "Can construct data service where clause on embedded object"() {
        given: "An object with an embedded field on it"
        def attribute = new PersonAttribute(contexts: [new AttributeContext(neighborhoodId: '1234')])
        attribute.save()
        manager.session.flush()
        manager.session.clear()
        def service = manager.session.datastore.getService(PersonAttributeDataService)

        when: "We query using the autogenerated where clause"
        def response = service.findByNeighborhoodId('1234')

        then: "The association is valid"
        response.size() == 1
        response.first().contexts.first().neighborhoodId == '1234'
    }
}

@Entity
class PersonAttribute {
    String id
    List<AttributeContext> contexts = []
    static embedded = ['contexts']
}

@Embeddable
class AttributeContext {

    String id
    String neighborhoodId

    static belongsTo = [attribute: PersonAttribute]

}

@Service(PersonAttribute)
interface PersonAttributeDataService {
    @Where({ contexts { neighborhoodId == neighborhoodId } })
    List<PersonAttribute> findByNeighborhoodId(String neighborhoodId)
}
