use roto_codegen::generator::generate_rust_code;
use roto_codegen::google::protobuf::compiler::plugin::CodeGeneratorRequest;
use roto_codegen::google::protobuf::descriptor::FileDescriptorSet;
use std::fs;

fn load_generated_code() -> String {
    let data = fs::read("data/request.bin").expect("Failed to read data/request.bin");
    let request = CodeGeneratorRequest::new(&data).expect("Failed to parse CodeGeneratorRequest");

    let mut set_buf = Vec::new();
    for file_res in request.proto_file() {
        let (file_data, _) = file_res.expect("Failed to iterate proto_file");
        set_buf.push(10u8);
        let len = file_data.len() as u64;
        let mut len_buf = [0u8; 10];
        let len_size = roto_runtime::write_varint(len, &mut len_buf).unwrap();
        set_buf.extend_from_slice(&len_buf[..len_size]);
        set_buf.extend_from_slice(file_data);
    }
    let set = FileDescriptorSet::new(&set_buf).expect("Failed to create FileDescriptorSet");

    generate_rust_code(&set, None, false)
        .into_iter()
        .map(|(_, content)| content)
        .collect()
}

#[test]
fn test_builder_structs_have_written_flags() {
    let code = load_generated_code();
    assert!(
        code.contains("_written: bool"),
        "Builder structs should contain `_written: bool` fields for each proto field"
    );
}

#[test]
fn test_builder_constructor_initialises_written_flags_to_false() {
    let code = load_generated_code();
    assert!(
        code.contains("_written: false"),
        "Builder constructors should initialise every `_written` flag to false"
    );
}

#[test]
fn test_builder_setters_mark_field_as_written() {
    let code = load_generated_code();
    assert!(
        code.contains("_written = true"),
        "Each builder setter should set its `_written` flag to true"
    );
}

#[test]
fn test_builder_has_with_method() {
    let code = load_generated_code();
    assert!(
        code.contains("pub fn with("),
        "Each builder impl should expose a `with` method"
    );
}

#[test]
fn test_message_structs_have_raw_fields_method() {
    let code = load_generated_code();
    assert!(
        code.contains("pub fn raw_fields("),
        "Each message struct impl should expose a `raw_fields` method"
    );
}

#[test]
fn test_with_method_uses_write_raw() {
    let code = load_generated_code();
    assert!(
        code.contains("write_raw(raw_bytes)"),
        "The `with` method should call `write_raw` to copy field bytes"
    );
}
