import json
from datetime import datetime, timezone
import logging

logger = logging.getLogger(__name__)

class RACCheckService:
    def __init__(self):
        self._rac_checks = []  # In-memory storage for demonstration

    def add_rac_check(self, customer_id, account_id, transaction_id, data=None):
        rac_check = {
            'id': len(self._rac_checks) + 1,
            'transaction_id': transaction_id,
            'customer_id': customer_id,
            'account_id': account_id,
            'rac_response': json.dumps(data or {}),
            'created_at': datetime.now(timezone.utc),
            'updated_at': datetime.now(timezone.utc)
        }
        self._rac_checks.append(rac_check)
        logger.info(f"Added RAC check: {rac_check}")
        return rac_check

    def get_all_rac_checks(self):
        logger.info(f"Retrieving all RAC checks. Count: {len(self._rac_checks)}")
        return self._rac_checks if self._rac_checks else None

    def get_rac_check(self, customer_id, account_id):
        for rac_check in self._rac_checks:
            if rac_check['customer_id'] == customer_id and rac_check['account_id'] == account_id:
                logger.info(f"Retrieved RAC check for customer_id={customer_id}, account_id={account_id}: {rac_check}")
                return rac_check
        logger.error(f"RAC Check for customer_id={customer_id}, account_id={account_id} not found")
        raise ValueError("RAC Check for customer not found")

    def to_dict(self, rac_check):
        logger.debug(f"Converting RAC check to dict: {rac_check}")
        return {
            "id": str(rac_check["id"]),
            "transactionId": str(rac_check["transaction_id"]),
            "customerId": rac_check["customer_id"],
            "accountId": rac_check["account_id"],
            "racResponse": json.loads(rac_check["rac_response"]),
            "createdAt": rac_check["created_at"].isoformat(),
            "updatedAt": rac_check["updated_at"].isoformat() if rac_check["updated_at"] else None
        } 