using System;
using Dirichlet.Mediation;
using Runtime.ADAggregator;
using UnityEngine;

internal static class TapadnAdRequestFactory
{
    public static bool TryParseSlotId(string slotId, out long parsed)
    {
        return long.TryParse(slotId, out parsed) && parsed > 0;
    }

    public static DirichletAdRequest BuildRewarded(string slotId, TapadnControllerOptions options)
    {
        var builder = CreateBaseBuilder(slotId)
            .WithUserId(ADManager.Instance.UserId)
            .WithRewardName(options?.RewardName ?? "reward")
            .WithRewardAmount(options?.RewardAmount ?? 1);

        return builder.Build();
    }

    public static DirichletAdRequest BuildInterstitial(string slotId, TapadnControllerOptions options)
    {
        return ApplyExpressSize(CreateBaseBuilder(slotId), options).Build();
    }

    public static DirichletAdRequest BuildSplash(string slotId, TapadnControllerOptions options)
    {
        var builder = CreateBaseBuilder(slotId);
        var width = options?.ExpressWidth ?? Screen.width;
        var height = options?.ExpressHeight ?? Screen.height;
        return builder.WithExpressViewSize(width, height).Build();
    }

    private static DirichletAdRequest.Builder CreateBaseBuilder(string slotId)
    {
        if (!TryParseSlotId(slotId, out var parsed))
        {
            throw new ArgumentException($"TapADN slot id must be a positive integer. Current value: {slotId}", nameof(slotId));
        }

        return new DirichletAdRequest.Builder().WithSpaceId(parsed);
    }

    private static DirichletAdRequest.Builder ApplyExpressSize(DirichletAdRequest.Builder builder, TapadnControllerOptions options)
    {
        if (options?.ExpressWidth != null || options?.ExpressHeight != null)
        {
            builder.WithExpressViewSize(options?.ExpressWidth ?? Screen.width, options?.ExpressHeight ?? Screen.height);
        }

        return builder;
    }
}
