using System.Text.Json;
using Tiku.Application.Security;
using Tiku.Domain.Operations;

namespace Tiku.Application.Backoffice;

public sealed record BackofficeActor(Guid UserId, Guid? TenantId, bool IsPlatform)
{
    public static BackofficeActor FromTenantAccess(CurrentAccessSnapshot access)
    {
        if (access.UserId is not { } userId ||
            access.TenantId is not { } tenantId ||
            !access.IsCurrentTenantMember)
        {
            throw new InvalidOperationException("Tenant backoffice actor was not resolved.");
        }

        return new BackofficeActor(userId, tenantId, false);
    }

    public static BackofficeActor FromPlatformAccess(CurrentAccessSnapshot access)
    {
        if (access.UserId is not { } userId || !access.IsUserActive)
        {
            throw new InvalidOperationException("Platform backoffice actor was not resolved.");
        }

        return new BackofficeActor(userId, null, true);
    }
}

public sealed record BackofficeBootstrap(
    IReadOnlyCollection<BackofficePermissionItem> Permissions,
    IReadOnlyCollection<BackofficeMenuItem> Menus,
    IReadOnlyCollection<BackofficeRoleItem> Roles);

public sealed record BackofficeUiBootstrap(
    IReadOnlyCollection<string> PermissionCodes,
    IReadOnlyCollection<BackofficeMenuItem> Menus,
    IReadOnlyCollection<string> EnabledFeatures,
    IReadOnlyCollection<FeatureQuotaSnapshot> Quotas);

public sealed record BackofficePermissionItem(
    Guid Id,
    string Code,
    string Name,
    BackendPermissionArea Area,
    string PermissionModuleCode,
    string? Description,
    int SortOrder);

public sealed record BackofficeMenuItem(
    Guid Id,
    string Code,
    string? ParentCode,
    string Title,
    BackendPermissionArea Area,
    string? Path,
    string? Icon,
    string? PermissionCode,
    int SortOrder,
    bool IsActive);

public sealed record BackofficeRoleItem(
    Guid Id,
    string Code,
    string Name,
    BackendRoleStatus Status,
    bool IsSystem,
    string? Description,
    IReadOnlyCollection<string> PermissionCodes,
    IReadOnlyCollection<string> MenuCodes,
    JsonElement? DataScope = null);

public sealed record UpsertBackofficeRoleCommand(
    Guid? Id,
    string Code,
    string Name,
    BackendRoleStatus Status,
    string? Description,
    JsonElement? DataScope = null);

public sealed record ReplaceRoleBindingsCommand(
    Guid RoleId,
    IReadOnlyCollection<string> PermissionCodes,
    IReadOnlyCollection<string> MenuCodes);

public sealed record ReplaceUserRolesCommand(
    Guid UserId,
    IReadOnlyCollection<Guid> RoleIds);

public sealed record BackofficeOperationAuditCommand(
    Guid? TenantId,
    Guid? ActorUserId,
    string Action,
    string? TargetType,
    string? TargetId,
    JsonElement Details,
    string? IpAddress = null,
    string? UserAgent = null);
