# Tests that nested for comprehensions within field patterns work correctly.
# The test uses a kubernetes-like structure with services and deployments.
-- in.cue --
package kube

service: "node-exporter": {
	spec: {
		ports: [{
			name:     "metrics"
			port:     9100
			protocol: "TCP"
		}]
	}
}
deployment: "node-exporter": {
	spec: template: {
		spec: {
			containers: [{
				ports: [{
					containerPort: 9100
					name:          "scrape"
				}]
			}]
		}
	}
	@test(eq, {
		spec: template: spec: containers: [{
			ports: [{
				_export$kube: _ @test(ignore)
				containerPort: 9100
				name:          "scrape"
			}]
			name: string
		}]
		_name$kube: string
	})
}
service: [ID=string]: {
	spec: {
		ports: [...{
			port:     int
			protocol: *"TCP" | "UDP"
			name:     string | *"client"
		}]
	}
}
deployment: [ID=string]: {}
deployment: [ID=_]: _spec & {}
_spec: {
	_name: string
	spec: template: {
		spec: containers: [{name: _name}]
	}
}
_spec: spec: template: spec: containers: [...{
	ports: [...{
		_export: *true | false // include the port in the service
	}]
}]
for k, v in deployment {
	service: "\(k)": {
		spec: selector: v.spec.template.metadata.labels
		spec: ports: [
			for c in v.spec.template.spec.containers
			for p in c.ports
			if p._export {
				let Port = p.containerPort // Port is an alias
				port:       *Port | int
				targetPort: *Port | int
			},
		]
	}
}
@test(eq, {
	service: "node-exporter": spec: {
		ports: [{
			name:       "metrics"
			port:       9100
			protocol:   "TCP"
			targetPort: *9100 | int
		}]
		selector: _|_ @test(err, code=incomplete, contains="service.\"node-exporter\".spec.selector: undefined field: metadata", pos=[-12:35])
	}
	deployment: "node-exporter": {
		spec: template: spec: containers: [{
			ports: [{
				containerPort: 9100
				name:          "scrape"
				_export$kube:  *true | false
			}]
			name: string
		}]
		_name$kube: string
	}
	_spec$kube: {
		_name$kube: string
		spec: template: spec: containers: [{
			name: string
			ports: []
		}]
	}
})

-- out/errors.txt --
[incomplete] service."node-exporter".spec.selector: undefined field: metadata:
    ./in.cue:59:35
-- out/eval/stats --
Leaks:  6
Freed:  40
Reused: 12
Allocs: 34
Retain: 0

Unifications: 35
Conjuncts:    89
Disjuncts:    10

NumCloseIDs: 5
