// Generated by Qleany v1.7.0 from entity_units_of_work.tera

use anyhow::{Ok, Result};
use common::database::{CommandUnitOfWork, QueryUnitOfWork};
use common::database::{db_context::DbContext, transactions::Transaction};
use common::direct_access::repository_factory;
use common::direct_access::use_cases;
use common::entities::Global;
use common::event::{AllEvent, DirectAccessEntity, Event, EventBuffer, EventHub, Origin};
use common::snapshot::EntityTreeSnapshot;
use common::types;
use common::types::EntityId;
use std::cell::RefCell;
use std::sync::Arc;

// ===========================================================================
// Write UoW
// ===========================================================================

pub struct GlobalWriteUoW {
    context: DbContext,
    transaction: Option<Transaction>,
    event_hub: Arc<EventHub>,
    event_buffer: RefCell<EventBuffer>,
}

impl GlobalWriteUoW {
    pub fn new(db_context: &DbContext, event_hub: &Arc<EventHub>) -> Self {
        GlobalWriteUoW {
            context: db_context.clone(),
            transaction: None,
            event_hub: event_hub.clone(),
            event_buffer: RefCell::new(EventBuffer::new()),
        }
    }
}

impl CommandUnitOfWork for GlobalWriteUoW {
    fn begin_transaction(&mut self) -> Result<()> {
        self.transaction = Some(Transaction::begin_write_transaction(&self.context)?);
        self.event_buffer.get_mut().begin_buffering();
        Ok(())
    }

    fn commit(&mut self) -> Result<()> {
        self.transaction
            .take()
            .ok_or_else(|| anyhow::anyhow!("No active transaction"))?
            .commit()?;
        for event in self.event_buffer.get_mut().flush() {
            self.event_hub.send_event(event);
        }
        Ok(())
    }

    fn rollback(&mut self) -> Result<()> {
        self.transaction
            .take()
            .ok_or_else(|| anyhow::anyhow!("No active transaction"))?
            .rollback()?;
        self.event_buffer.get_mut().discard();
        Ok(())
    }

    fn create_savepoint(&self) -> Result<types::Savepoint> {
        self.transaction
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("No active transaction"))?
            .create_savepoint()
    }

    fn restore_to_savepoint(&mut self, savepoint: types::Savepoint) -> Result<()> {
        let mut transaction = self
            .transaction
            .take()
            .ok_or_else(|| anyhow::anyhow!("No active transaction"))?;
        transaction.restore_to_savepoint(savepoint)?;

        // Discard buffered events — savepoint restore invalidated them
        self.event_buffer.get_mut().discard();

        // Send Reset immediately (not buffered — UI must refresh now)
        self.event_hub.send_event(Event {
            origin: Origin::DirectAccess(DirectAccessEntity::All(AllEvent::Reset)),
            ids: vec![],
            data: None,
        });

        // Recreate the transaction after restoring to savepoint
        self.transaction = Some(transaction);

        Ok(())
    }
}

impl use_cases::WriteUoW for GlobalWriteUoW {
    type Entity = Global;

    fn get(&self, id: &EntityId) -> Result<Option<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_global_repository(transaction)?;
        Ok(repo.get(id)?)
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_global_repository(transaction)?;
        Ok(repo.get_multi(ids)?)
    }

    fn get_all(&self) -> Result<Vec<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_global_repository(transaction)?;
        Ok(repo.get_all()?)
    }

    fn create_orphan_multi(&self, entities: &[Global]) -> Result<Vec<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.create_orphan_multi(&mut event_buffer, entities)?)
    }

    fn update_multi(&self, entities: &[Global]) -> Result<Vec<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.update_multi(&mut event_buffer, entities)?)
    }

    fn update_with_relationships_multi(&self, entities: &[Global]) -> Result<Vec<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.update_with_relationships_multi(&mut event_buffer, entities)?)
    }

    fn remove(&self, id: &EntityId) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.remove(&mut event_buffer, id)?)
    }

    fn remove_multi(&self, ids: &[EntityId]) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.remove_multi(&mut event_buffer, ids)?)
    }

    fn snapshot(&self, ids: &[EntityId]) -> Result<EntityTreeSnapshot> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_global_repository(transaction)?;
        Ok(repo.snapshot(ids)?)
    }

    fn restore(&self, snap: &EntityTreeSnapshot) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.restore(&mut event_buffer, snap)?)
    }
}

impl use_cases::OwnedWriteUoW for GlobalWriteUoW {
    fn create_multi(
        &self,
        entities: &[Global],
        owner_id: EntityId,
        index: i32,
    ) -> Result<Vec<Global>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        Ok(repo.create_multi(&mut event_buffer, entities, owner_id, index)?)
    }

    fn get_relationships_from_owner(&self, owner_id: &EntityId) -> Result<Vec<EntityId>> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let repo = repository_factory::write::create_global_repository(transaction)?;
        Ok(repo.get_relationships_from_owner(owner_id)?)
    }

    fn set_relationships_in_owner(&self, owner_id: &EntityId, ids: &[EntityId]) -> Result<()> {
        let transaction = self.transaction.as_ref().expect("Transaction not started");
        let mut repo = repository_factory::write::create_global_repository(transaction)?;
        let mut event_buffer = self.event_buffer.borrow_mut();
        repo.set_relationships_in_owner(&mut event_buffer, owner_id, ids)?;
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Write UoW Factory
// ---------------------------------------------------------------------------

pub struct GlobalWriteUoWFactory {
    context: DbContext,
    event_hub: Arc<EventHub>,
}

impl GlobalWriteUoWFactory {
    pub fn new(db_context: &DbContext, event_hub: &Arc<EventHub>) -> Self {
        GlobalWriteUoWFactory {
            context: db_context.clone(),
            event_hub: event_hub.clone(),
        }
    }
}

impl use_cases::WriteUoWFactory for GlobalWriteUoWFactory {
    type Entity = Global;
    fn create(&self) -> Box<dyn use_cases::WriteUoW<Entity = Global>> {
        Box::new(GlobalWriteUoW::new(&self.context, &self.event_hub))
    }
}

impl use_cases::OwnedWriteUoWFactory for GlobalWriteUoWFactory {
    type Entity = Global;
    fn create(&self) -> Box<dyn use_cases::OwnedWriteUoW<Entity = Global>> {
        Box::new(GlobalWriteUoW::new(&self.context, &self.event_hub))
    }
}

// ===========================================================================
// Read-Only UoW
// ===========================================================================

pub struct GlobalReadUoW {
    context: DbContext,
    transaction: RefCell<Option<Transaction>>,
}

impl GlobalReadUoW {
    pub fn new(db_context: &DbContext) -> Self {
        GlobalReadUoW {
            context: db_context.clone(),
            transaction: RefCell::new(None),
        }
    }
}

impl QueryUnitOfWork for GlobalReadUoW {
    fn begin_transaction(&self) -> Result<()> {
        self.transaction
            .replace(Some(Transaction::begin_read_transaction(&self.context)?));
        Ok(())
    }

    fn end_transaction(&self) -> Result<()> {
        self.transaction
            .take()
            .ok_or_else(|| anyhow::anyhow!("No active transaction"))?
            .end_read_transaction()?;
        Ok(())
    }
}

impl use_cases::ReadUoW for GlobalReadUoW {
    type Entity = Global;

    fn get(&self, id: &EntityId) -> Result<Option<Global>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_global_repository(
            transaction
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("No active transaction"))?,
        )?;
        Ok(repo.get(id)?)
    }

    fn get_multi(&self, ids: &[EntityId]) -> Result<Vec<Option<Global>>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_global_repository(
            transaction
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("No active transaction"))?,
        )?;
        Ok(repo.get_multi(ids)?)
    }

    fn get_all(&self) -> Result<Vec<Global>> {
        let transaction = self.transaction.borrow();
        let repo = repository_factory::read::create_global_repository(
            transaction
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("No active transaction"))?,
        )?;
        Ok(repo.get_all()?)
    }
}

// ---------------------------------------------------------------------------
// Read-Only UoW Factory
// ---------------------------------------------------------------------------

pub struct GlobalReadUoWFactory {
    context: DbContext,
}

impl GlobalReadUoWFactory {
    pub fn new(db_context: &DbContext) -> Self {
        GlobalReadUoWFactory {
            context: db_context.clone(),
        }
    }
}

impl use_cases::ReadUoWFactory for GlobalReadUoWFactory {
    type Entity = Global;
    fn create(&self) -> Box<dyn use_cases::ReadUoW<Entity = Global>> {
        Box::new(GlobalReadUoW::new(&self.context))
    }
}
