//! Transaction attribute macro — marks transaction function boundaries.
//!
//! The `#[transaction(name)]` attribute validates that the transaction name
//! exists in the concept map (via `CONCEPT_MAP_TRANSACTIONS` env var set by
//! `mad_hatter_guardian::activate()` in build.rs).
//!
//! This macro serves as:
//! 1. Compile-time validation of transaction names
//! 2. A marker for Guardian's E008 unguarded_io detection

use proc_macro2::TokenStream;
use syn::{
    parse::{Parse, ParseStream},
    Ident,
};

// ── #[transaction(name)] ──

pub struct TransactionAttr {
    tx_name: String,
}

impl Parse for TransactionAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let ident: Ident = input.parse()?;
        Ok(TransactionAttr {
            tx_name: ident.to_string(),
        })
    }
}

pub fn expand_transaction_attr(attr: TransactionAttr, item: TokenStream) -> TokenStream {
    // Try to validate against CONCEPT_MAP_TRANSACTIONS env var
    // (set by mad_hatter_guardian::activate() in build.rs)
    if let Ok(names_csv) = std::env::var("CONCEPT_MAP_TRANSACTIONS") {
        let valid: Vec<&str> = names_csv.split(',').collect();
        if !valid.contains(&attr.tx_name.as_str()) {
            let msg = format!(
                "Transaction '{}' not found in concept map. Available: {:?}",
                attr.tx_name, valid
            );
            return syn::Error::new(proc_macro2::Span::call_site(), msg).to_compile_error();
        }
    }
    // If env var not set, skip validation (backward compatibility).
    // Guardian E008 still enforces at build.rs level.

    // Return original function unchanged — the attribute is a marker
    item
}