use anyhow::Result;
use std::path::PathBuf;
use std::{env, fs};

const OUT_DIR: &str = "tests/generated";
const PROTOS: &[&str] = &[
    "account.proto",
    "access_token.proto",
    "linked_account.proto",
    "type_salad.proto",
];
const PREFIXES: &[&str] = &[".acme.user.v1"];

fn main() -> Result<()> {
    // Generate protobuf sources
    fs::create_dir_all(OUT_DIR)?;
    let descriptor_path = PathBuf::from(env::var("OUT_DIR").unwrap_or_default()).join("proto_descriptor.bin");
    tonic_prost_build::configure()
        .out_dir(OUT_DIR)
        .file_descriptor_set_path(&descriptor_path)
        .protoc_arg("--experimental_allow_proto3_optional")
        .compile_well_known_types(true)
        .extern_path(".google.protobuf", "::pbjson_types")
        .compile_protos(PROTOS, &["./proto"])?;

    // Generate pbjson serde support
    let descriptor_set = std::fs::read(descriptor_path)?;
    pbjson_build::Builder::new()
        .out_dir(OUT_DIR)
        .register_descriptors(&descriptor_set)?
        .ignore_unknown_fields()
        .emit_fields()
        .build(PREFIXES)?;

    Ok(())
}
