use anyhow::Result;

use crate::auth_profile::AuthSchemeKind;
use crate::context::GeneratorContext;
use crate::targets::go::context::GoTemplateContext;
use crate::targets::go::emit::render_and_write;
use crate::targets::go::render::render_engine;

/// Always emitted, regardless of which schemes were discovered.
const SHARED_FILES: &[(&str, &str)] = &[
    (
        "internal/auth/strategy.go.tera",
        "internal/auth/strategy.go",
    ),
    ("internal/auth/errors.go.tera", "internal/auth/errors.go"),
    (
        "internal/auth/requestcredentials.go.tera",
        "internal/auth/requestcredentials.go",
    ),
    ("internal/auth/stub.go.tera", "internal/auth/stub.go"),
    ("internal/auth/manager.go.tera", "internal/auth/manager.go"),
    (
        "internal/auth/register.go.tera",
        "internal/auth/register.go",
    ),
];

/// One strategy file per discovered `AuthSchemeKind`; content depends only
/// on the kind, not the scheme's declared name, so kinds are deduplicated
/// before rendering (a spec can declare more than one scheme of the same
/// kind, e.g. two `apiKey` schemes). Mirrors
/// `targets::csharp::steps::auth::strategy_template`.
fn strategy_template(kind: AuthSchemeKind) -> (&'static str, &'static str) {
    match kind {
        AuthSchemeKind::Basic => ("internal/auth/basic.go.tera", "internal/auth/basic.go"),
        AuthSchemeKind::ApiKey => ("internal/auth/apikey.go.tera", "internal/auth/apikey.go"),
        AuthSchemeKind::BearerPat => ("internal/auth/pat.go.tera", "internal/auth/pat.go"),
        AuthSchemeKind::OAuth2 => ("internal/auth/oauth2.go.tera", "internal/auth/oauth2.go"),
        AuthSchemeKind::OAuth1 => ("internal/auth/oauth1.go.tera", "internal/auth/oauth1.go"),
    }
}

/// `generate_auth_strategies` (architecture.md §1, step 7): one strategy
/// implementation per discovered `AuthSchemeDescriptor`, registered in
/// `internal/auth/register.go`, plus the `Manager` that selects the single
/// active strategy from config at runtime.
pub async fn generate_auth_strategies(ctx: &GeneratorContext) -> Result<()> {
    let view = GoTemplateContext::from_context(ctx);
    let tera = render_engine()?;
    let tera_ctx = tera::Context::from_serialize(&view)?;

    for (template, out_name) in SHARED_FILES {
        render_and_write(&tera, template, &tera_ctx, &ctx.output_dir.join(out_name)).await?;
    }

    let mut emitted_kinds: Vec<AuthSchemeKind> = Vec::new();
    for scheme in &ctx.auth_schemes {
        if emitted_kinds.contains(&scheme.kind) {
            continue;
        }
        emitted_kinds.push(scheme.kind);

        let (template, out_name) = strategy_template(scheme.kind);
        render_and_write(&tera, template, &tera_ctx, &ctx.output_dir.join(out_name)).await?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use std::path::{Path, PathBuf};

    use super::*;
    use crate::auth_profile::{AuthSchemeDescriptor, default_location_for};

    fn ctx_with_schemes(
        output_dir: PathBuf,
        auth_schemes: Vec<AuthSchemeDescriptor>,
    ) -> GeneratorContext {
        GeneratorContext {
            publish_registry: false,
            openapi_input: "spec.yaml".to_string(),
            output_dir,
            force: false,
            output_dir_preexisted: false,
            auth_schemes,
            normalized_operations: Vec::new(),
            api_title: "Widget API".to_string(),
            version_label: "default".to_string(),
        }
    }

    fn descriptor(name: &str, kind: AuthSchemeKind) -> AuthSchemeDescriptor {
        AuthSchemeDescriptor {
            name: name.to_string(),
            kind,
            location: default_location_for(kind),
        }
    }

    fn output_dir(parent: &tempfile::TempDir) -> PathBuf {
        parent.path().join("output")
    }

    fn file_exists(dir: &Path, relative: &str) -> bool {
        dir.join(relative).is_file()
    }

    #[tokio::test]
    async fn basic_and_oauth2_fixture_emits_exactly_the_expected_files() {
        let parent = tempfile::tempdir().unwrap();
        let dir = output_dir(&parent);
        let ctx = ctx_with_schemes(
            dir.clone(),
            vec![
                descriptor("basicAuth", AuthSchemeKind::Basic),
                descriptor("oauth2", AuthSchemeKind::OAuth2),
            ],
        );

        generate_auth_strategies(&ctx).await.unwrap();

        for expected in [
            "internal/auth/strategy.go",
            "internal/auth/errors.go",
            "internal/auth/requestcredentials.go",
            "internal/auth/stub.go",
            "internal/auth/manager.go",
            "internal/auth/register.go",
            "internal/auth/basic.go",
            "internal/auth/oauth2.go",
        ] {
            assert!(file_exists(&dir, expected), "missing {expected}");
        }

        for undiscovered in [
            "internal/auth/pat.go",
            "internal/auth/oauth1.go",
            "internal/auth/apikey.go",
        ] {
            assert!(
                !file_exists(&dir, undiscovered),
                "unexpected {undiscovered}"
            );
        }
    }

    #[tokio::test]
    async fn all_four_kinds_fixture_emits_every_strategy_and_registers_each_key() {
        let parent = tempfile::tempdir().unwrap();
        let dir = output_dir(&parent);
        let ctx = ctx_with_schemes(
            dir.clone(),
            vec![
                descriptor("basicAuth", AuthSchemeKind::Basic),
                descriptor("pat", AuthSchemeKind::BearerPat),
                descriptor("oauth1", AuthSchemeKind::OAuth1),
                descriptor("oauth2", AuthSchemeKind::OAuth2),
            ],
        );

        generate_auth_strategies(&ctx).await.unwrap();

        for expected in [
            "internal/auth/basic.go",
            "internal/auth/pat.go",
            "internal/auth/oauth1.go",
            "internal/auth/oauth2.go",
        ] {
            assert!(file_exists(&dir, expected), "missing {expected}");
        }
        assert!(!file_exists(&dir, "internal/auth/apikey.go"));

        let registrations = tokio::fs::read_to_string(dir.join("internal/auth/register.go"))
            .await
            .unwrap();
        assert!(registrations.contains("core.AuthMethodBasic] = BasicStrategy{}"));
        assert!(registrations.contains("core.AuthMethodPat] = PatStrategy{}"));
        assert!(registrations.contains("core.AuthMethodOAuth1] = OAuth1Strategy{}"));
        assert!(registrations.contains("core.AuthMethodOAuth2] = OAuth2Strategy{}"));
        assert!(
            !registrations.contains("ApiKeyStrategy"),
            "must not register an undiscovered strategy"
        );
        assert!(
            !registrations.contains("core.AuthMethodNone] ="),
            "must not register the stub fallback when real schemes were discovered"
        );

        let manager = tokio::fs::read_to_string(dir.join("internal/auth/manager.go"))
            .await
            .unwrap();
        assert!(manager.contains("core.AuthMethodOAuth1"));
    }

    #[tokio::test]
    async fn duplicate_scheme_kind_only_emits_one_strategy_file() {
        let parent = tempfile::tempdir().unwrap();
        let dir = output_dir(&parent);
        let ctx = ctx_with_schemes(
            dir.clone(),
            vec![
                descriptor("apiKeyOne", AuthSchemeKind::ApiKey),
                descriptor("apiKeyTwo", AuthSchemeKind::ApiKey),
            ],
        );

        generate_auth_strategies(&ctx).await.unwrap();

        assert!(file_exists(&dir, "internal/auth/apikey.go"));
    }

    #[tokio::test]
    async fn no_schemes_registers_stub_under_auth_method_none() {
        let parent = tempfile::tempdir().unwrap();
        let dir = output_dir(&parent);
        let ctx = ctx_with_schemes(dir.clone(), Vec::new());

        generate_auth_strategies(&ctx).await.unwrap();

        let registrations = tokio::fs::read_to_string(dir.join("internal/auth/register.go"))
            .await
            .unwrap();
        assert!(registrations.contains("core.AuthMethodNone] = StubStrategy{}"));

        let manager = tokio::fs::read_to_string(dir.join("internal/auth/manager.go"))
            .await
            .unwrap();
        assert!(
            !manager.contains("core.AuthMethodOAuth1"),
            "must not reference core.AuthMethodOAuth1 when it wasn't discovered"
        );
    }
}
