use crate::Result;
use crate::name::RunName;
use crate::store::{NewResource, OperationId, ResourceId, ResourceRow, ResourceState, Scope, Tx};
use super::Found;
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Recorded {
pub(crate) made: Vec<ResourceId>,
pub(crate) gone: Vec<ResourceId>,
}
pub(crate) fn record_found(tx: &mut Tx<'_>, run: &RunName, by: OperationId, found: &[Found]) -> Result<Recorded> {
let live: Vec<ResourceRow> = tx.live_resources(run)?.into_iter().filter(|r| r.scope == Scope::Provider).collect();
let mut recorded = Recorded::default();
for f in found {
let row = live
.iter()
.find(|r| r.key == f.key && r.kind == f.kind && r.native_id.as_deref().is_none_or(|id| id == f.native_id));
match row {
Some(r) if r.state == ResourceState::Destroying || (r.state == ResourceState::Created && r.native_id.as_deref() == Some(f.native_id.as_str())) => {}
Some(r) => {
tx.created(r.id, &f.native_id)?;
recorded.made.push(r.id);
}
None => {
let id = tx.creating(&NewResource::new(run, &f.key, f.kind, by).living(f.lifetime))?;
tx.created(id, &f.native_id)?;
recorded.made.push(id);
}
}
}
for r in &live {
let still = found
.iter()
.any(|f| f.key == r.key && f.kind == r.kind && r.native_id.as_deref().is_none_or(|id| id == f.native_id));
if !still && r.native_id.is_some() {
if r.state != ResourceState::Destroying {
tx.destroying(r.id, by)?;
}
tx.gone(r.id)?;
recorded.gone.push(r.id);
}
}
Ok(recorded)
}
pub(crate) fn left_to_remove(tx: &Tx<'_>, run: &RunName) -> Result<Vec<ResourceRow>> {
Ok(tx
.live_resources(run)?
.into_iter()
.filter(|r| r.scope == Scope::Provider && r.native_id.is_some())
.collect())
}
#[cfg(test)]
mod tests;