use rusqlite::{params, Connection};

use crate::error::{AppError, AppResult};
use crate::shared::types::Lang;

pub struct RemovedItemRecord {
    pub _removal_id: String,
    pub table_name: String,
    pub entity_id: String,
    pub book_id: Option<String>,
    pub _user_id: String,
    pub deleted_at: i64,
}

/// Inserts a removal record into the database.
/// * `conn` - Database connection
/// * `removal_id` - The unique ID for this removal record
/// * `table_name` - The name of the table from which the item is deleted
/// * `entity_id` - The UUID of the deleted entity
/// * `book_id` - Book ID (None for series items)
/// * `user_id` - The user ID who owns the item
/// * `deleted_at` - Timestamp of deletion
/// * `lang` - The language for error messages ("fr" or "en")
/// Returns true if inserted successfully.
pub fn insert(
    conn: &Connection, removal_id: &str, table_name: &str, entity_id: &str,
    book_id: Option<&str>, user_id: &str, deleted_at: i64, lang: Lang,
) -> AppResult<bool> {
    let insert_result = conn
        .execute(
            "INSERT INTO removed_items (removal_id, table_name, entity_id, book_id, user_id, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(table_name, entity_id) DO UPDATE SET deleted_at = excluded.deleted_at",
            params![removal_id, table_name, entity_id, book_id, user_id, deleted_at],
        )
        .map_err(|_| AppError::Internal(if lang == Lang::Fr { "Impossible d'enregistrer la suppression.".to_string() } else { "Unable to record deletion.".to_string() }))?;

    Ok(insert_result > 0)
}

/// Retrieves deletions since a specific timestamp.
/// Used to get deletions that occurred since last sync.
/// * `conn` - Database connection
/// * `user_id` - The user ID
/// * `since` - Timestamp to get deletions after
/// * `lang` - The language for error messages ("fr" or "en")
/// Returns array of removed item records.
pub fn get_deletions_since(conn: &Connection, user_id: &str, since: i64, lang: Lang) -> AppResult<Vec<RemovedItemRecord>> {
    let mut statement = conn
        .prepare("SELECT removal_id, table_name, entity_id, book_id, user_id, deleted_at FROM removed_items WHERE user_id = ?1 AND deleted_at > ?2")
        .map_err(|_| AppError::Internal(if lang == Lang::Fr { "Impossible de récupérer les suppressions.".to_string() } else { "Unable to retrieve deletions.".to_string() }))?;

    let records = statement
        .query_map(params![user_id, since], |query_row| {
            Ok(RemovedItemRecord {
                _removal_id: query_row.get(0)?, table_name: query_row.get(1)?,
                entity_id: query_row.get(2)?, book_id: query_row.get(3)?,
                _user_id: query_row.get(4)?, deleted_at: query_row.get(5)?,
            })
        })
        .map_err(|_| AppError::Internal(if lang == Lang::Fr { "Impossible de récupérer les suppressions.".to_string() } else { "Unable to retrieve deletions.".to_string() }))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|_| AppError::Internal(if lang == Lang::Fr { "Impossible de récupérer les suppressions.".to_string() } else { "Unable to retrieve deletions.".to_string() }))?;

    Ok(records)
}

