// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Microsoft.Teams.Api.Activities;
using Microsoft.Teams.Apps.Routing;

namespace Microsoft.Teams.Apps.Activities;

[AttributeUsage(AttributeTargets.Method, Inherited = true)]
public class InstallAttribute() : InstallUpdateAttribute(InstallUpdateAction.Add)
{
    public override bool Select(IActivity activity)
    {
        if (activity is InstallUpdateActivity installUpdate)
        {
            return installUpdate.Action.IsAdd;
        }

        return false;
    }
}

public static partial class AppActivityExtensions
{
    public static App OnInstall(this App app, Func<IContext<InstallUpdateActivity>, Task> handler)
    {
        app.Router.Register(new Route()
        {
            Name = string.Join("/", [ActivityType.InstallUpdate, InstallUpdateAction.Add]),
            Type = app.Status is null ? RouteType.System : RouteType.User,
            Handler = async context =>
            {
                await handler(context.ToActivityType<InstallUpdateActivity>());
                return null;
            },
            Selector = activity =>
            {
                if (activity is InstallUpdateActivity installUpdate)
                {
                    return installUpdate.Action.IsAdd;
                }

                return false;
            }
        });

        return app;
    }

    public static App OnInstall(this App app, Func<IContext<InstallUpdateActivity>, CancellationToken, Task> handler)
    {
        app.Router.Register(new Route()
        {
            Name = string.Join("/", [ActivityType.InstallUpdate, InstallUpdateAction.Add]),
            Type = app.Status is null ? RouteType.System : RouteType.User,
            Handler = async context =>
            {
                await handler(context.ToActivityType<InstallUpdateActivity>(), context.CancellationToken);
                return null;
            },
            Selector = activity =>
            {
                if (activity is InstallUpdateActivity installUpdate)
                {
                    return installUpdate.Action.IsAdd;
                }

                return false;
            }
        });

        return app;
    }
}