//! Rails 6+ Active Storage attachment macros —
//! `has_one_attached`, `has_many_attached`.
//!
//! Emits accessor Method Symbols (`avatar`, `avatar=`) and Defines edges
//! from the declaring class.

use ckg_core::{Edge, EdgeKind, Kind};
use tree_sitter::Node;

use crate::lang::ruby::{Ctx, strip_quotes, text};

/// `has_one_attached :avatar` / `has_many_attached :photos` (Rails 6+).
/// Emits accessor methods (`avatar`, `avatar=`, `avatar_attachment`, …) —
/// minimal subset: just the name + `=` setter.
pub(crate) fn handle_attachment(
    ctx: &mut Ctx<'_>,
    n: Node<'_>,
    src: &str,
    macro_name: &str,
    scope: &str,
    class_id: &str,
    is_public: bool,
) {
    let _ = macro_name;
    let Some(args) = n.child_by_field_name("arguments") else {
        return;
    };
    let mut c = args.walk();
    for arg in args.children(&mut c) {
        if arg.kind() != "simple_symbol" {
            continue;
        }
        let base = strip_quotes(text(arg, src)).to_string();
        for name in [base.clone(), format!("{base}=")] {
            let qname = if scope.is_empty() {
                format!("{}.{name}", ctx.module)
            } else {
                format!("{}::{scope}.{name}", ctx.module)
            };
            let id = ctx.push_with_visibility(arg, src, Kind::Method, qname, name, is_public);
            ctx.out.edges.push(Edge {
                kind: EdgeKind::Defines,
                src: class_id.to_string(),
                dst: id,
                confidence: 1.0,
            });
        }
        return;
    }
}
