using System.Text.Json;
using Tiku.Domain.Tenancy;

namespace Tiku.Application.Tenancy;

public sealed record TenantExternalProviderAccount(
    Guid TenantId,
    TenantExternalProviderCapability Capability,
    string Provider,
    TenantExternalProviderStatus Status,
    string? DisplayName,
    JsonElement ConfigPublic,
    JsonElement SecretPayload,
    string? SecretRef,
    int Priority,
    JsonElement Metadata);

public sealed record UpsertTenantExternalProviderCommand(
    TenantExternalProviderCapability Capability,
    string Provider,
    TenantExternalProviderStatus Status,
    string? DisplayName,
    string? SecretRef,
    int? Priority,
    JsonElement ConfigPublic,
    JsonElement Metadata);

public sealed record TenantExternalProviderItem(
    Guid Id,
    TenantExternalProviderCapability Capability,
    string Provider,
    TenantExternalProviderStatus Status,
    string? DisplayName,
    string? SecretRef,
    int Priority,
    JsonElement ConfigPublic,
    JsonElement Metadata,
    DateTimeOffset CreatedAt,
    DateTimeOffset UpdatedAt);

public interface ITenantExternalProviderConfigService
{
    Task<TenantExternalProviderAccount> GetActiveProviderAsync(
        Guid tenantId,
        TenantExternalProviderCapability capability,
        string? provider = null,
        CancellationToken cancellationToken = default);

    Task<IReadOnlyCollection<TenantExternalProviderItem>> GetProvidersAsync(
        Guid tenantId,
        TenantExternalProviderCapability? capability = null,
        string? provider = null,
        int? limit = null,
        CancellationToken cancellationToken = default);

    Task<TenantExternalProviderItem> UpsertProviderAsync(
        Guid tenantId,
        UpsertTenantExternalProviderCommand command,
        CancellationToken cancellationToken = default);
}

public sealed class TenantExternalProviderException(string message, string code) : Exception(message)
{
    public string Code { get; } = code;
}