// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Immutable;

using Analyzer.Utilities.Extensions;

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;

using MSTest.Analyzers.Helpers;

namespace MSTest.Analyzers;

/// <summary>
/// MSTEST0030: <inheritdoc cref="Resources.TypeContainingTestMethodShouldBeATestClassTitle"/>.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class TypeContainingTestMethodShouldBeATestClassAnalyzer : DiagnosticAnalyzer
{
    private static readonly LocalizableResourceString Title = new(nameof(Resources.TypeContainingTestMethodShouldBeATestClassTitle), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableResourceString Description = new(nameof(Resources.TypeContainingTestMethodShouldBeATestClassDescription), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.TypeContainingTestMethodShouldBeATestClassMessageFormat), Resources.ResourceManager, typeof(Resources));

    internal static readonly DiagnosticDescriptor TypeContainingTestMethodShouldBeATestClassRule = DiagnosticDescriptorHelper.Create(
        DiagnosticIds.TypeContainingTestMethodShouldBeATestClassRuleId,
        Title,
        MessageFormat,
        Description,
        Category.Usage,
        DiagnosticSeverity.Warning,
        isEnabledByDefault: true);

    /// <inheritdoc />
    public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
        = ImmutableArray.Create(TypeContainingTestMethodShouldBeATestClassRule);

    /// <inheritdoc />
    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();

        context.RegisterCompilationStartAction(context =>
        {
            if (context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute, out INamedTypeSymbol? testMethodAttributeSymbol)
                && context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestClassAttribute, out INamedTypeSymbol? testClassAttributeSymbol))
            {
                context.RegisterSymbolAction(
                    context => AnalyzeSymbol(context, testClassAttributeSymbol, testMethodAttributeSymbol),
                    SymbolKind.NamedType);
            }
        });
    }

    private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol testClassAttributeSymbol, INamedTypeSymbol testMethodAttributeSymbol)
    {
        var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
        if ((namedTypeSymbol.TypeKind != TypeKind.Class && namedTypeSymbol.TypeKind != TypeKind.Struct)
            || namedTypeSymbol.IsAbstract)
        {
            return;
        }

        bool isTestClass = namedTypeSymbol.IsTestClass(testClassAttributeSymbol);

        if (isTestClass)
        {
            return;
        }

        bool hasTestMethod = false;
        INamedTypeSymbol? currentType = namedTypeSymbol;
        while (currentType is not null && !hasTestMethod)
        {
            foreach (ISymbol classMember in currentType.GetMembers())
            {
                if (classMember.Kind != SymbolKind.Method)
                {
                    continue;
                }

                foreach (AttributeData attribute in classMember.GetAttributes())
                {
                    if (attribute.AttributeClass.Inherits(testMethodAttributeSymbol))
                    {
                        hasTestMethod = true;
                        break;
                    }
                }
            }

            currentType = currentType.BaseType;
        }

        if (!hasTestMethod)
        {
            return;
        }

        context.ReportDiagnostic(namedTypeSymbol.CreateDiagnostic(TypeContainingTestMethodShouldBeATestClassRule, namedTypeSymbol.Name));
    }
}
