/*
 * transaction.c
 *
 *  Created on: 2026-03-04
 *      Author: RT-Thread
 *
 *  功能: 事务管理模块实现
 *  依赖: RT-Thread Nano, osal
 *  跨平台适配: 基于RT-Thread Nano，使用标准API
 */

#include <rtthread.h>
#include "osal.h"
#include "transaction.h"

/* 事务数组 */
static transaction_t g_transactions[MAX_TRANSACTIONS];

/**
 * @brief 初始化事务管理
 * @return 0 成功，非0 失败
 */
int transaction_init(void)
{
    /* 初始化事务数组 */
    for (int i = 0; i < MAX_TRANSACTIONS; i++)
    {
        g_transactions[i].id = 0;
        g_transactions[i].status = TRANSACTION_STATUS_IDLE;
        g_transactions[i].rollback_func = NULL;
        g_transactions[i].user_data = NULL;
    }
    
    osal_log_i("Transaction management initialized");
    return 0;
}

/**
 * @brief 开始事务
 * @param rollback_func 回滚函数
 * @param user_data 用户数据
 * @return 事务ID，失败返回0
 */
int transaction_begin(transaction_rollback_func_t rollback_func, void *user_data)
{
    /* 查找空闲事务 */
    int id = 0;
    for (int i = 0; i < MAX_TRANSACTIONS; i++)
    {
        if (g_transactions[i].status == TRANSACTION_STATUS_IDLE)
        {
            id = i + 1; /* 事务ID从1开始 */
            break;
        }
    }
    
    if (id == 0)
    {
        osal_log_e("No free transaction available");
        return 0;
    }
    
    /* 初始化事务 */
    g_transactions[id - 1].id = id;
    g_transactions[id - 1].status = TRANSACTION_STATUS_ACTIVE;
    g_transactions[id - 1].rollback_func = rollback_func;
    g_transactions[id - 1].user_data = user_data;
    
    osal_log_i("Transaction %d started", id);
    return id;
}

/**
 * @brief 提交事务
 * @param id 事务ID
 * @return 0 成功，非0 失败
 */
int transaction_commit(int id)
{
    if (id < 1 || id > MAX_TRANSACTIONS)
    {
        return -1;
    }
    
    transaction_t *tx = &g_transactions[id - 1];
    if (tx->status != TRANSACTION_STATUS_ACTIVE)
    {
        return -1;
    }
    
    /* 提交事务 */
    tx->status = TRANSACTION_STATUS_IDLE;
    tx->rollback_func = NULL;
    tx->user_data = NULL;
    
    osal_log_i("Transaction %d committed", id);
    return 0;
}

/**
 * @brief 回滚事务
 * @param id 事务ID
 * @return 0 成功，非0 失败
 */
int transaction_rollback(int id)
{
    if (id < 1 || id > MAX_TRANSACTIONS)
    {
        return -1;
    }
    
    transaction_t *tx = &g_transactions[id - 1];
    if (tx->status != TRANSACTION_STATUS_ACTIVE)
    {
        return -1;
    }
    
    /* 执行回滚函数 */
    if (tx->rollback_func != NULL)
    {
        osal_log_i("Rolling back transaction %d", id);
        tx->rollback_func(tx->user_data);
    }
    
    /* 重置事务状态 */
    tx->status = TRANSACTION_STATUS_IDLE;
    tx->rollback_func = NULL;
    tx->user_data = NULL;
    
    osal_log_i("Transaction %d rolled back", id);
    return 0;
}

/**
 * @brief 获取事务状态
 * @param id 事务ID
 * @return 事务状态
 */
transaction_status_t transaction_get_status(int id)
{
    if (id < 1 || id > MAX_TRANSACTIONS)
    {
        return TRANSACTION_STATUS_INVALID;
    }
    
    return g_transactions[id - 1].status;
}
