using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace foodmarket.Api.Seed;

public class OpenIddictClientSeeder : IHostedService
{
    public const string WebClientId = "food-market-web";
    public const string PosClientId = "food-market-pos";

    private readonly IServiceProvider _services;

    public OpenIddictClientSeeder(IServiceProvider services)
    {
        _services = services;
    }

    public async Task StartAsync(CancellationToken ct)
    {
        using var scope = _services.CreateScope();
        var mgr = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();

        if (await mgr.FindByClientIdAsync(WebClientId, ct) is null)
        {
            await mgr.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = WebClientId,
                DisplayName = "food-market web admin",
                ClientType = ClientTypes.Public,
                Permissions =
                {
                    Permissions.Endpoints.Token,
                    Permissions.GrantTypes.Password,
                    Permissions.GrantTypes.RefreshToken,
                    Permissions.Scopes.Email,
                    Permissions.Scopes.Profile,
                    Permissions.Scopes.Roles,
                    Permissions.Prefixes.Scope + "api",
                }
            }, ct);
        }

        if (await mgr.FindByClientIdAsync(PosClientId, ct) is null)
        {
            await mgr.CreateAsync(new OpenIddictApplicationDescriptor
            {
                ClientId = PosClientId,
                DisplayName = "food-market POS client",
                ClientType = ClientTypes.Public,
                Permissions =
                {
                    Permissions.Endpoints.Token,
                    Permissions.GrantTypes.Password,
                    Permissions.GrantTypes.RefreshToken,
                    Permissions.Scopes.Email,
                    Permissions.Scopes.Profile,
                    Permissions.Scopes.Roles,
                    Permissions.Prefixes.Scope + "api",
                }
            }, ct);
        }
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}
