using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Tiku.Application.Growth;
using Tiku.Application.Security;
using Tiku.Domain.Commerce;
using Tiku.Domain.Common;
using Tiku.Domain.Growth;
using Tiku.Domain.Operations;
using Tiku.Domain.Tenancy;
using Tiku.Infrastructure.Persistence;

namespace Tiku.Infrastructure.Growth;

public sealed class CommissionService(
    TikuDbContext dbContext,
    ICurrentAccessContext currentAccessContext) : ICommissionService
{
    public async Task<CommissionSettingsItem> GetSettingsAsync(CommissionAdminActor actor, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        return ToSettingsItem(await GetSettingsCoreAsync(actor.TenantId, cancellationToken));
    }

    public async Task<CommissionSettingsItem> UpdateSettingsAsync(CommissionAdminActor actor, UpdateCommissionSettingsCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var settings = await GetSettingsCoreAsync(actor.TenantId, cancellationToken);
        settings.DefaultRate = command.DefaultRate ?? settings.DefaultRate;
        settings.MinSettlementCents = command.MinSettlementCents ?? settings.MinSettlementCents;
        settings.SettlementCycle = ParseEnum(command.SettlementCycle, settings.SettlementCycle, "invalid_commission_cycle");
        settings.Config = command.Config ?? settings.Config;
        settings.UpdatedBy = actor.UserId;
        await dbContext.SaveChangesAsync(cancellationToken);
        return ToSettingsItem(settings);
    }

    public async Task<object> UpdateMemberRateAsync(CommissionAdminActor actor, UpdateMemberCommissionRateCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var member = await dbContext.TenantMemberships
            .FirstOrDefaultAsync(item => item.TenantId == actor.TenantId && item.UserId == command.UserId, cancellationToken)
            ?? throw new CommissionException("Commission member was not found.", "commission_member_not_found");
        var settings = await GetSettingsCoreAsync(actor.TenantId, cancellationToken);
        var config = settings.Config.ValueKind == JsonValueKind.Object
            ? JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(settings.Config.GetRawText()) ?? []
            : [];
        var memberRates = config.TryGetValue("memberRates", out var existingRates) && existingRates.ValueKind == JsonValueKind.Object
            ? JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(existingRates.GetRawText()) ?? []
            : [];
        memberRates[member.UserId.ToString("N")] = JsonSerializer.SerializeToElement(new
        {
            commissionRate = command.CommissionRate,
            commissionConfig = command.CommissionConfig
        });
        config["memberRates"] = JsonSerializer.SerializeToElement(memberRates);
        settings.Config = JsonSerializer.SerializeToElement(config);
        await dbContext.SaveChangesAsync(cancellationToken);
        return new { member.UserId, commissionRate = command.CommissionRate, commissionConfig = command.CommissionConfig };
    }

    public async Task<CommissionSummaryItem> GetSummaryAsync(CommissionAdminActor actor, CommissionPeriodQuery query, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var rows = await BuildSourcesAsync(actor.TenantId, query, cancellationToken);
        return new CommissionSummaryItem(
            rows.Count,
            rows.Select(item => item.StudentUserId).Where(id => id.HasValue).Distinct().Count(),
            rows.Sum(item => item.GrossAmountCents),
            rows.Sum(item => item.CommissionAmountCents));
    }

    public async Task<CommissionList<CommissionSourceItem>> GetOrdersAsync(CommissionAdminActor actor, CommissionPeriodQuery query, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var rows = await BuildSourcesAsync(actor.TenantId, query, cancellationToken);
        return new CommissionList<CommissionSourceItem>(rows.Take(Math.Clamp(query.Limit ?? 100, 1, 500)).Select(ToSourceItem).ToArray());
    }

    public async Task<CommissionList<CommissionSettlementItemDto>> GetSettlementsAsync(CommissionAdminActor actor, CommissionSettlementQuery query, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var items = dbContext.CommissionSettlements.AsNoTracking().Where(item => item.TenantId == actor.TenantId);
        if (query.ReferrerUserId.HasValue) items = items.Where(item => item.ReferrerUserId == query.ReferrerUserId.Value);
        if (!string.IsNullOrWhiteSpace(query.Status)) items = items.Where(item => item.Status == ParseEnum(query.Status, CommissionSettlementStatus.Draft, "invalid_commission_status"));
        var result = await items.OrderByDescending(item => item.CreatedAt).Take(Math.Clamp(query.Limit ?? 100, 1, 500)).ToArrayAsync(cancellationToken);
        return new CommissionList<CommissionSettlementItemDto>(result.Select(ToSettlementItem).ToArray());
    }

    public async Task<CommissionExportItem> ExportSettlementAsync(CommissionAdminActor actor, Guid settlementId, string? format, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var settlement = await GetSettlementAsync(actor.TenantId, settlementId, cancellationToken);
        var items = await dbContext.CommissionSettlementItems.AsNoTracking()
            .Where(item => item.TenantId == actor.TenantId && item.SettlementId == settlementId)
            .OrderBy(item => item.SourcePaidAt)
            .ToArrayAsync(cancellationToken);
        var resolvedFormat = string.Equals(format, "json", StringComparison.OrdinalIgnoreCase) ? "json" : "csv";
        var content = resolvedFormat == "json"
            ? JsonSerializer.Serialize(items.Select(ToSourceItem))
            : BuildCsv(items);
        var bytes = Encoding.UTF8.GetBytes(content);
        var sha = Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant();
        var filename = $"{settlement.SettlementNo}.{resolvedFormat}";
        dbContext.CommissionSettlementExportEvents.Add(new CommissionSettlementExportEvent
        {
            TenantId = actor.TenantId,
            SettlementId = settlementId,
            ExportedBy = actor.UserId,
            ExportFormat = resolvedFormat,
            Filename = filename,
            RowCount = items.Length,
            ContentSha256 = sha,
            Metadata = JsonSerializer.SerializeToElement(new { sizeBytes = bytes.Length })
        });
        await AddAuditAsync(actor, "commission.settlement.exported", "commission_settlements", settlementId, new { format = resolvedFormat, filename, rowCount = items.Length, sha }, cancellationToken);
        await dbContext.SaveChangesAsync(cancellationToken);
        return new CommissionExportItem(settlementId, filename, resolvedFormat, resolvedFormat == "json" ? "application/json" : "text/csv", items.Length, Convert.ToBase64String(bytes), sha, bytes.Length);
    }

    public async Task<CommissionSettlementItemDto> GenerateSettlementAsync(CommissionAdminActor actor, GenerateCommissionSettlementCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        if (command.EndDate < command.StartDate) throw new CommissionException("Commission period was invalid.", "invalid_commission_period");
        var query = new CommissionPeriodQuery(command.StartDate, command.EndDate, command.ReferrerUserId, 5000);
        var candidates = (await BuildSourcesAsync(actor.TenantId, query, cancellationToken)).Where(item => item.SettlementId is null).ToArray();
        if (candidates.Length == 0) throw new CommissionException("No unsettled commission sources found.", "commission_no_unsettled_sources");
        var settings = await GetSettingsCoreAsync(actor.TenantId, cancellationToken);
        var amount = candidates.Sum(item => item.CommissionAmountCents);
        if (amount < settings.MinSettlementCents) throw new CommissionException("Commission amount is below settlement minimum.", "commission_below_minimum");
        var settlement = new CommissionSettlement
        {
            TenantId = actor.TenantId,
            ReferrerUserId = command.ReferrerUserId,
            GeneratedBy = actor.UserId,
            SettlementNo = $"CS{DateTimeOffset.UtcNow:yyyyMMddHHmmss}{RandomNumberGenerator.GetInt32(1000, 9999)}",
            Status = ParseEnum(command.Status, CommissionSettlementStatus.PendingReview, "invalid_commission_status"),
            PeriodStart = command.StartDate,
            PeriodEnd = command.EndDate,
            SourceCount = candidates.Length,
            PaidUserCount = candidates.Select(item => item.StudentUserId).Where(id => id.HasValue).Distinct().Count(),
            GrossAmountCents = candidates.Sum(item => item.GrossAmountCents),
            CommissionAmountCents = amount,
            DefaultRate = settings.DefaultRate,
            Remark = command.Remark,
            Metadata = command.Metadata ?? JsonDefaults.Object()
        };
        dbContext.CommissionSettlements.Add(settlement);
        foreach (var source in candidates)
        {
            dbContext.CommissionSettlementItems.Add(new CommissionSettlementItem
            {
                TenantId = actor.TenantId,
                SettlementId = settlement.Id,
                ReferrerUserId = source.ReferrerUserId,
                StudentUserId = source.StudentUserId,
                SourceType = source.SourceType,
                SourceId = source.SourceId,
                SourceNo = source.SourceNo,
                SourcePaidAt = source.SourcePaidAt,
                GrossAmountCents = source.GrossAmountCents,
                CommissionRate = source.CommissionRate,
                CommissionAmountCents = source.CommissionAmountCents,
                RateSource = source.RateSource,
                AttributionType = source.AttributionType,
                Metadata = JsonSerializer.SerializeToElement(new { source = "commission_generate" })
            });
        }
        await dbContext.SaveChangesAsync(cancellationToken);
        return ToSettlementItem(settlement);
    }

    public async Task<CommissionSettlementItemDto> UpdateSettlementStatusAsync(CommissionAdminActor actor, UpdateCommissionSettlementStatusCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var item = await GetSettlementAsync(actor.TenantId, command.SettlementId, cancellationToken);
        var status = ParseEnum(command.Status, CommissionSettlementStatus.Approved, "invalid_commission_status");
        if (item.Status == CommissionSettlementStatus.Paid && status != CommissionSettlementStatus.Paid)
            throw new CommissionException("Paid settlement cannot be reverted.", "commission_status_invalid");
        item.Status = status;
        item.Remark = command.ReviewNote ?? item.Remark;
        item.Metadata = command.Metadata ?? item.Metadata;
        if (status is CommissionSettlementStatus.Approved or CommissionSettlementStatus.Rejected or CommissionSettlementStatus.Cancelled)
        {
            item.ReviewedBy = actor.UserId;
            item.ReviewedAt = DateTimeOffset.UtcNow;
        }
        if (status == CommissionSettlementStatus.Paid)
        {
            item.PaidBy = actor.UserId;
            item.PaidAt = DateTimeOffset.UtcNow;
            item.PaymentMethod = command.PaymentMethod ?? item.PaymentMethod;
            item.PaymentAccount = command.PaymentAccount ?? item.PaymentAccount;
        }
        await dbContext.SaveChangesAsync(cancellationToken);
        return ToSettlementItem(item);
    }

    public async Task<CommissionList<CommissionProofItem>> GetProofsAsync(CommissionAdminActor actor, Guid settlementId, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        await GetSettlementAsync(actor.TenantId, settlementId, cancellationToken);
        var items = await dbContext.CommissionSettlementProofs.AsNoTracking()
            .Where(item => item.TenantId == actor.TenantId && item.SettlementId == settlementId)
            .OrderByDescending(item => item.CreatedAt)
            .ToArrayAsync(cancellationToken);
        return new CommissionList<CommissionProofItem>(items.Select(ToProofItem).ToArray());
    }

    public async Task<CommissionProofItem> CreateProofAsync(CommissionAdminActor actor, CreateCommissionProofCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var settlement = await GetSettlementAsync(actor.TenantId, command.SettlementId, cancellationToken);
        var proof = new CommissionSettlementProof
        {
            TenantId = actor.TenantId,
            SettlementId = command.SettlementId,
            SubmittedBy = actor.UserId,
            ProofType = ParseEnum(command.ProofType, CommissionProofType.Payment, "invalid_commission_proof_type"),
            Status = CommissionProofStatus.Submitted,
            Title = command.Title ?? $"{settlement.SettlementNo} 打款凭证",
            Description = command.Description,
            AssetId = command.AssetId,
            ExternalUrl = command.ExternalUrl,
            AmountCents = command.AmountCents ?? settlement.CommissionAmountCents,
            PaymentMethod = command.PaymentMethod,
            PaymentAccount = command.PaymentAccount,
            PaidAt = command.PaidAt,
            Metadata = command.Metadata ?? JsonDefaults.Object()
        };
        dbContext.CommissionSettlementProofs.Add(proof);
        await dbContext.SaveChangesAsync(cancellationToken);
        return ToProofItem(proof);
    }

    public async Task<CommissionProofItem> UpdateProofStatusAsync(CommissionAdminActor actor, UpdateCommissionProofStatusCommand command, CancellationToken cancellationToken = default)
    {
        await AssertAdminAsync(actor, cancellationToken);
        var proof = await dbContext.CommissionSettlementProofs.FirstOrDefaultAsync(item => item.TenantId == actor.TenantId && item.Id == command.ProofId, cancellationToken)
            ?? throw new CommissionException("Commission proof was not found.", "commission_proof_not_found");
        var status = ParseEnum(command.Status, CommissionProofStatus.Approved, "invalid_commission_proof_status");
        if (status == CommissionProofStatus.Submitted) throw new CommissionException("Cannot move proof back to submitted.", "invalid_commission_proof_status");
        if (proof.Status is CommissionProofStatus.Approved or CommissionProofStatus.Rejected or CommissionProofStatus.Voided && proof.Status != status)
            throw new CommissionException("Closed proof cannot change status.", "commission_proof_closed");
        proof.Status = status;
        proof.ReviewedBy = actor.UserId;
        proof.ReviewedAt = DateTimeOffset.UtcNow;
        proof.ReviewNote = command.ReviewNote ?? proof.ReviewNote;
        proof.Metadata = command.Metadata ?? proof.Metadata;
        await dbContext.SaveChangesAsync(cancellationToken);
        return ToProofItem(proof);
    }

    private async Task<IReadOnlyCollection<SourceCandidate>> BuildSourcesAsync(Guid tenantId, CommissionPeriodQuery query, CancellationToken cancellationToken)
    {
        var today = DateOnly.FromDateTime(DateTime.UtcNow);
        var startDate = query.StartDate ?? today.AddDays(-29);
        var endDate = query.EndDate ?? today;
        var start = new DateTimeOffset(startDate.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc));
        var end = new DateTimeOffset(endDate.AddDays(1).ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc));
        var settings = await GetSettingsCoreAsync(tenantId, cancellationToken);
        var existing = await dbContext.CommissionSettlementItems.AsNoTracking()
            .Where(item => item.TenantId == tenantId)
            .Select(item => new { item.SourceType, item.SourceId, item.SettlementId })
            .ToArrayAsync(cancellationToken);
        var result = new List<SourceCandidate>();
        var orders = await (
            from order in dbContext.Orders.AsNoTracking()
            join lead in dbContext.ReferralLeads.AsNoTracking()
                on new { order.TenantId, StudentUserId = order.UserId!.Value } equals new { lead.TenantId, lead.StudentUserId }
            where order.TenantId == tenantId && order.UserId != null && lead.ReferrerUserId != null &&
                  order.Status == OrderStatus.Paid && order.PaidAt >= start && order.PaidAt < end
            select new { order, lead })
            .ToArrayAsync(cancellationToken);
        foreach (var row in orders)
        {
            if (query.ReferrerUserId.HasValue && row.lead.ReferrerUserId != query.ReferrerUserId) continue;
            var rate = GetMemberRate(settings.Config, row.lead.ReferrerUserId!.Value) ?? settings.DefaultRate;
            var settled = existing.FirstOrDefault(item => item.SourceType == CommissionSourceType.Order && item.SourceId == row.order.Id)?.SettlementId;
            result.Add(new SourceCandidate(CommissionSourceType.Order, row.order.Id, row.order.OrderNo, row.lead.ReferrerUserId.Value, row.order.UserId, row.order.AmountCents, rate, (int)Math.Round(row.order.AmountCents * rate), CommissionRateSource.Member, settled, row.order.PaidAt, "protected_lead"));
        }
        var codes = await (
            from code in dbContext.ActivationCodes.AsNoTracking()
            join batch in dbContext.CodeBatches.AsNoTracking()
                on new { code.TenantId, BatchId = code.BatchId } equals new { batch.TenantId, BatchId = (Guid?)batch.Id } into batches
            from batch in batches.DefaultIfEmpty()
            where code.TenantId == tenantId && code.IsUsed && code.AgentUserId != null && code.UsedAt >= start && code.UsedAt < end
            select new { code, batch })
            .ToArrayAsync(cancellationToken);
        foreach (var row in codes)
        {
            if (!row.code.AgentUserId.HasValue) continue;
            var agentUserId = row.code.AgentUserId.Value;
            if (query.ReferrerUserId.HasValue && agentUserId != query.ReferrerUserId) continue;
            var rate = row.batch?.CommissionRate ?? GetMemberRate(settings.Config, agentUserId) ?? settings.DefaultRate;
            var sourceAmount = row.code.UnitPriceCents ?? row.batch?.DefaultUnitPriceCents ?? 0;
            var settled = existing.FirstOrDefault(item => item.SourceType == CommissionSourceType.ActivationCode && item.SourceId == row.code.Id)?.SettlementId;
            result.Add(new SourceCandidate(CommissionSourceType.ActivationCode, row.code.Id, row.code.Code, agentUserId, row.code.UsedBy, sourceAmount, rate, (int)Math.Round(sourceAmount * rate), row.batch?.CommissionRate is null ? CommissionRateSource.Member : CommissionRateSource.Batch, settled, row.code.UsedAt, "activation_code_agent"));
        }
        return result.OrderBy(item => item.SourcePaidAt).ToArray();
    }

    private static decimal? GetMemberRate(JsonElement config, Guid userId)
    {
        if (config.ValueKind != JsonValueKind.Object ||
            !config.TryGetProperty("memberRates", out var memberRates) ||
            memberRates.ValueKind != JsonValueKind.Object ||
            !memberRates.TryGetProperty(userId.ToString("N"), out var memberRate) ||
            memberRate.ValueKind != JsonValueKind.Object ||
            !memberRate.TryGetProperty("commissionRate", out var value) ||
            value.ValueKind != JsonValueKind.Number ||
            !value.TryGetDecimal(out var rate))
        {
            return null;
        }

        return rate;
    }

    private async Task<TenantCommissionSetting> GetSettingsCoreAsync(Guid tenantId, CancellationToken cancellationToken)
    {
        var settings = await dbContext.TenantCommissionSettings.FirstOrDefaultAsync(item => item.TenantId == tenantId, cancellationToken);
        if (settings is not null) return settings;
        settings = new TenantCommissionSetting { TenantId = tenantId };
        dbContext.TenantCommissionSettings.Add(settings);
        return settings;
    }

    private async Task<CommissionSettlement> GetSettlementAsync(Guid tenantId, Guid settlementId, CancellationToken cancellationToken) =>
        await dbContext.CommissionSettlements.FirstOrDefaultAsync(item => item.TenantId == tenantId && item.Id == settlementId, cancellationToken)
        ?? throw new CommissionException("Commission settlement was not found.", "commission_settlement_not_found");

    private async Task AssertAdminAsync(CommissionAdminActor actor, CancellationToken cancellationToken)
    {
        var access = await currentAccessContext.GetAsync(cancellationToken);
        if (!access.IsCurrentTenantMember ||
            access.TenantId != actor.TenantId ||
            access.UserId != actor.UserId ||
            !access.HasTenantPermission(BackendPermissions.TenantCommissionManage))
        {
            throw new CommissionException("Commission admin access was denied.", "commission_access_denied");
        }
    }

    private async Task AddAuditAsync(CommissionAdminActor actor, string action, string targetType, Guid targetId, object details, CancellationToken cancellationToken)
    {
        dbContext.AuditLogs.Add(new AuditLog { TenantId = actor.TenantId, ActorUserId = actor.UserId, Action = action, TargetType = targetType, TargetId = targetId.ToString(), Details = JsonSerializer.SerializeToElement(details) });
        await Task.CompletedTask.WaitAsync(cancellationToken);
    }

    private static string BuildCsv(IEnumerable<CommissionSettlementItem> items)
    {
        var builder = new StringBuilder("sourceType,sourceNo,referrerUserId,studentUserId,grossAmountCents,commissionRate,commissionAmountCents\n");
        foreach (var item in items)
            builder.Append(CultureInfo.InvariantCulture, $"{item.SourceType},{item.SourceNo},{item.ReferrerUserId},{item.StudentUserId},{item.GrossAmountCents},{item.CommissionRate},{item.CommissionAmountCents}\n");
        return builder.ToString();
    }

    private static CommissionSettingsItem ToSettingsItem(TenantCommissionSetting item) => new(item.DefaultRate, item.MinSettlementCents, item.SettlementCycle.ToString(), item.Config);
    private static CommissionSourceItem ToSourceItem(SourceCandidate item) => new(item.SourceType.ToString(), item.SourceId, item.SourceNo, item.ReferrerUserId, item.StudentUserId, item.GrossAmountCents, item.CommissionRate, item.CommissionAmountCents, item.RateSource.ToString(), item.SettlementId);
    private static CommissionSourceItem ToSourceItem(CommissionSettlementItem item) => new(item.SourceType.ToString(), item.SourceId, item.SourceNo, item.ReferrerUserId, item.StudentUserId, item.GrossAmountCents, item.CommissionRate, item.CommissionAmountCents, item.RateSource.ToString(), item.SettlementId);
    private static CommissionSettlementItemDto ToSettlementItem(CommissionSettlement item) => new(item.Id, item.SettlementNo, item.ReferrerUserId, item.Status.ToString(), item.PeriodStart, item.PeriodEnd, item.SourceCount, item.PaidUserCount, item.GrossAmountCents, item.CommissionAmountCents, item.ReviewedAt, item.PaidAt);
    private static CommissionProofItem ToProofItem(CommissionSettlementProof item) => new(item.Id, item.SettlementId, item.ProofType.ToString(), item.Status.ToString(), item.Title, item.AssetId, item.ExternalUrl, item.AmountCents, item.PaymentMethod, item.PaymentAccount, item.PaidAt, item.ReviewedAt);

    private static TEnum ParseEnum<TEnum>(string? value, TEnum defaultValue, string errorCode) where TEnum : struct, Enum
    {
        if (string.IsNullOrWhiteSpace(value)) return defaultValue;
        var normalized = value.Replace("_", string.Empty, StringComparison.Ordinal);
        foreach (var enumValue in Enum.GetValues<TEnum>())
            if (string.Equals(enumValue.ToString(), normalized, StringComparison.OrdinalIgnoreCase)) return enumValue;
        throw new CommissionException("Commission enum value was invalid.", errorCode);
    }

    private sealed record SourceCandidate(CommissionSourceType SourceType, Guid SourceId, string? SourceNo, Guid ReferrerUserId, Guid? StudentUserId, int GrossAmountCents, decimal CommissionRate, int CommissionAmountCents, CommissionRateSource RateSource, Guid? SettlementId, DateTimeOffset? SourcePaidAt, string AttributionType);
}
