// Generated by Qleany v1.4.8 from feature_use_case.tera
use super::search_helpers::{build_full_text_via_store, find_all_matches};
use crate::FindResultDto;
use crate::FindTextDto;
use anyhow::{Result, anyhow};
use common::database::QueryUnitOfWork;
use common::database::rope_helpers::rope_flat_text_if_simple;
use common::direct_access::document::document_repository::DocumentRelationshipField;
use common::direct_access::frame::frame_repository::FrameRelationshipField;
use common::direct_access::root::root_repository::RootRelationshipField;
#[allow(unused_imports)]
use common::entities::{Block, Document, Frame, Root};
use common::types::{EntityId, ROOT_ENTITY_ID};

pub trait FindTextUnitOfWorkFactoryTrait: Send + Sync {
    fn create(&self) -> Box<dyn FindTextUnitOfWorkTrait>;
}

#[macros::uow_action(entity = "Root", action = "GetRO")]
#[macros::uow_action(entity = "Root", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Document", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Frame", action = "GetRelationshipRO")]
#[macros::uow_action(entity = "Block", action = "GetMultiRO")]
pub trait FindTextUnitOfWorkTrait: QueryUnitOfWork {}

/// Fetch all blocks from the document via the UoW, sort them, and build the full text.
fn build_full_text(uow: &dyn FindTextUnitOfWorkTrait) -> Result<String> {
    let root = uow
        .get_root(&ROOT_ENTITY_ID)?
        .ok_or_else(|| anyhow!("Root entity not found"))?;

    let doc_ids = uow.get_root_relationship(&root.id, &RootRelationshipField::Document)?;
    let doc_id = *doc_ids
        .first()
        .ok_or_else(|| anyhow!("Root has no document"))?;

    let frame_ids = uow.get_document_relationship(&doc_id, &DocumentRelationshipField::Frames)?;

    // Fast path: flat single-frame document — entire searchable text
    // is already laid out contiguously in the rope.
    if let Some(text) = rope_flat_text_if_simple(&uow.store(), frame_ids.len()) {
        return Ok(text);
    }

    let mut all_block_ids: Vec<EntityId> = Vec::new();
    for frame_id in &frame_ids {
        let block_ids = uow.get_frame_relationship(frame_id, &FrameRelationshipField::Blocks)?;
        all_block_ids.extend(block_ids);
    }

    let blocks_opt = uow.get_block_multi(&all_block_ids)?;
    let mut blocks: Vec<Block> = blocks_opt.into_iter().flatten().collect();
    blocks.sort_by_key(|b| b.document_position);

    Ok(build_full_text_via_store(&blocks, &uow.store()))
}

pub struct FindTextUseCase {
    uow_factory: Box<dyn FindTextUnitOfWorkFactoryTrait>,
}

impl FindTextUseCase {
    pub fn new(uow_factory: Box<dyn FindTextUnitOfWorkFactoryTrait>) -> Self {
        FindTextUseCase { uow_factory }
    }

    pub fn execute(&mut self, dto: &FindTextDto) -> Result<FindResultDto> {
        let uow = self.uow_factory.create();
        uow.begin_transaction()?;

        let full_text = build_full_text(uow.as_ref())?;

        let all_matches = find_all_matches(
            &full_text,
            &dto.query,
            dto.case_sensitive,
            dto.whole_word,
            dto.use_regex,
        )?;

        let start_pos = dto.start_position.max(0) as usize;

        let result = if dto.search_backward {
            all_matches
                .iter()
                .rev()
                .find(|(pos, _)| *pos < start_pos)
                .copied()
        } else {
            all_matches
                .iter()
                .find(|(pos, _)| *pos >= start_pos)
                .copied()
        };

        uow.end_transaction()?;

        match result {
            Some((pos, len)) => Ok(FindResultDto {
                found: true,
                position: pos as i64,
                length: len as i64,
            }),
            None => Ok(FindResultDto {
                found: false,
                position: 0,
                length: 0,
            }),
        }
    }
}
