// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

import "@openzeppelin/contracts/access/Ownable.sol";

/**
 * @title Multi-Signature Wallet
 * @notice Simple multi-sig implementation for admin operations
 * @dev For production, consider using Gnosis Safe or similar battle-tested solution
 */
contract MultiSig is Ownable {
    address[] public owners;
    mapping(address => bool) public isOwner;
    uint256 public required;
    
    struct Transaction {
        address to;
        uint256 value;
        bytes data;
        bool executed;
        uint256 confirmations;
    }
    
    Transaction[] public transactions;
    mapping(uint256 => mapping(address => bool)) public confirmations;
    
    event Confirmation(address indexed sender, uint256 indexed transactionId);
    event Revocation(address indexed sender, uint256 indexed transactionId);
    event Submission(uint256 indexed transactionId);
    event Execution(uint256 indexed transactionId);
    event ExecutionFailure(uint256 indexed transactionId);
    event OwnerAddition(address indexed owner);
    event OwnerRemoval(address indexed owner);
    event RequirementChange(uint256 required);
    
    modifier onlyWallet() {
        require(msg.sender == address(this), "MultiSig: only wallet");
        _;
    }
    
    modifier ownerDoesNotExist(address owner) {
        require(!isOwner[owner], "MultiSig: owner exists");
        _;
    }
    
    modifier ownerExists(address owner) {
        require(isOwner[owner], "MultiSig: owner does not exist");
        _;
    }
    
    modifier transactionExists(uint256 transactionId) {
        require(transactions[transactionId].to != address(0), "MultiSig: transaction does not exist");
        _;
    }
    
    modifier confirmed(uint256 transactionId, address owner) {
        require(confirmations[transactionId][owner], "MultiSig: not confirmed");
        _;
    }
    
    modifier notConfirmed(uint256 transactionId, address owner) {
        require(!confirmations[transactionId][owner], "MultiSig: already confirmed");
        _;
    }
    
    modifier notExecuted(uint256 transactionId) {
        require(!transactions[transactionId].executed, "MultiSig: already executed");
        _;
    }
    
    modifier validRequirement(uint256 ownerCount, uint256 _required) {
        require(_required <= ownerCount && _required > 0 && ownerCount > 0, "MultiSig: invalid requirement");
        _;
    }
    
    /**
     * @notice Constructor sets initial owners and required confirmations
     */
    constructor(address[] memory _owners, uint256 _required) Ownable(msg.sender) validRequirement(_owners.length, _required) {
        for (uint256 i = 0; i < _owners.length; i++) {
            require(_owners[i] != address(0) && !isOwner[_owners[i]], "MultiSig: invalid owner");
            isOwner[_owners[i]] = true;
            owners.push(_owners[i]);
        }
        required = _required;
    }
    
    /**
     * @notice Submit a transaction
     */
    function submitTransaction(address to, uint256 value, bytes memory data) external ownerExists(msg.sender) returns (uint256 transactionId) {
        transactionId = transactions.length;
        transactions.push(Transaction({
            to: to,
            value: value,
            data: data,
            executed: false,
            confirmations: 0
        }));
        emit Submission(transactionId);
        confirmTransaction(transactionId);
        return transactionId;
    }
    
    /**
     * @notice Confirm a transaction
     */
    function confirmTransaction(uint256 transactionId) public ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) {
        confirmations[transactionId][msg.sender] = true;
        transactions[transactionId].confirmations++;
        emit Confirmation(msg.sender, transactionId);
    }
    
    /**
     * @notice Revoke a confirmation
     */
    function revokeConfirmation(uint256 transactionId) external ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) {
        confirmations[transactionId][msg.sender] = false;
        transactions[transactionId].confirmations--;
        emit Revocation(msg.sender, transactionId);
    }
    
    /**
     * @notice Execute a confirmed transaction
     */
    function executeTransaction(uint256 transactionId) external ownerExists(msg.sender) notExecuted(transactionId) {
        require(transactions[transactionId].confirmations >= required, "MultiSig: insufficient confirmations");
        Transaction storage txn = transactions[transactionId];
        txn.executed = true;
        
        (bool success, ) = txn.to.call{value: txn.value}(txn.data);
        if (success) {
            emit Execution(transactionId);
        } else {
            emit ExecutionFailure(transactionId);
            txn.executed = false;
        }
    }
    
    /**
     * @notice Add a new owner
     */
    function addOwner(address owner) external onlyWallet ownerDoesNotExist(owner) {
        isOwner[owner] = true;
        owners.push(owner);
        emit OwnerAddition(owner);
    }
    
    /**
     * @notice Remove an owner
     */
    function removeOwner(address owner) external onlyWallet ownerExists(owner) {
        isOwner[owner] = false;
        for (uint256 i = 0; i < owners.length - 1; i++) {
            if (owners[i] == owner) {
                owners[i] = owners[owners.length - 1];
                break;
            }
        }
        owners.pop();
        if (required > owners.length) {
            changeRequirement(owners.length);
        }
        emit OwnerRemoval(owner);
    }
    
    /**
     * @notice Change the number of required confirmations
     */
    function changeRequirement(uint256 _required) public onlyWallet validRequirement(owners.length, _required) {
        required = _required;
        emit RequirementChange(_required);
    }
    
    /**
     * @notice Get transaction count
     */
    function getTransactionCount() external view returns (uint256) {
        return transactions.length;
    }
    
    /**
     * @notice Get owners
     */
    function getOwners() external view returns (address[] memory) {
        return owners;
    }
    
    /**
     * @notice Get transaction details
     */
    function getTransaction(uint256 transactionId) external view returns (
        address to,
        uint256 value,
        bytes memory data,
        bool executed,
        uint256 requiredConfirmations
    ) {
        Transaction storage txn = transactions[transactionId];
        return (txn.to, txn.value, txn.data, txn.executed, txn.confirmations);
    }
    
    /**
     * @notice Check if transaction is confirmed
     */
    function isConfirmed(uint256 transactionId) public view returns (bool) {
        return transactions[transactionId].confirmations >= required;
    }
}

