using Microsoft.Extensions.Configuration;
using Tiku.Application.Security;

namespace Tiku.Api.Options;

public static class OptionsValidation
{
    public static string ResolveDatabaseConnectionString(
        IConfiguration configuration,
        bool isDevelopment)
    {
        var connectionString =
            configuration.GetConnectionString("Database") ??
            configuration["DATABASE_URL"];
        if (!string.IsNullOrWhiteSpace(connectionString))
        {
            return connectionString;
        }

        if (isDevelopment)
        {
            return $"Host=localhost;Database=tiku;Username={Environment.UserName}";
        }

        throw new InvalidOperationException(
            "Database connection is required outside Development. Configure ConnectionStrings:Database or DATABASE_URL.");
    }

    public static bool BeValidJwtOptions(JwtOptions options, bool isProduction)
    {
        return JwtOptions.BeValid(options, isProduction);
    }

    public static bool BeValidCorsOptions(CorsOptions options)
    {
        if (options.AllowCredentials && options.AllowedOrigins.Length == 0)
        {
            return false;
        }

        return options.AllowedOrigins.All(IsHttpOrigin);
    }

    private static bool IsHttpOrigin(string origin)
    {
        return Uri.TryCreate(origin, UriKind.Absolute, out var uri) &&
               (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) &&
               string.IsNullOrEmpty(uri.PathAndQuery.Trim('/'));
    }
}
