using Microsoft.EntityFrameworkCore;
using MiGu.DB.Abstractions.Exceptions;
using MiGu.DB.Abstractions.Persistence;
using MiGu.Server.Persistence;

namespace MiGu.Server.Wms;

public sealed class WmsTransportRuleService
{
    private readonly PlatformDbContext _db;
    private readonly IEditableRepository<WmsTransportRule> _rules;
    private readonly IUnitOfWork _uow;

    public WmsTransportRuleService(
        PlatformDbContext db,
        IEditableRepository<WmsTransportRule> rules,
        IUnitOfWork uow)
    {
        _db = db;
        _rules = rules;
        _uow = uow;
    }

    public Task<List<WmsTransportRule>> ListAsync(string? triggerType = null, string? q = null)
    {
        var query = _db.WmsTransportRules.AsNoTracking().OrderByDescending(x => x.Priority).ThenBy(x => x.Code).AsQueryable();
        if (!string.IsNullOrWhiteSpace(triggerType) &&
            Enum.TryParse<WmsTransportTriggerType>(triggerType.Trim(), true, out var tt) &&
            WmsTransportTriggerTypes.All.Contains(tt))
            query = query.Where(x => x.TriggerType == tt);
        if (!string.IsNullOrWhiteSpace(q))
        {
            var s = q.Trim();
            query = query.Where(x => x.Code.Contains(s) || x.Name.Contains(s));
        }
        return query.ToListAsync();
    }

    public async Task<WmsTransportRule> SaveAsync(TransportRuleRequest req, string actor)
    {
        if (!WmsTransportTriggerTypes.IsDefined(req.TriggerType))
            throw new InvalidOperationException("触发类型无效");

        WmsTransportRule entity;
        if (req.Id.HasValue)
            entity = await _rules.GetEditableAsync(req.Id.Value, req.Version);
        else
        {
            entity = new WmsTransportRule();
            StampCreate(entity, actor);
            _db.WmsTransportRules.Add(entity);
        }

        await _rules.EnsureUniqueAsync(x => x.Code == req.Code.Trim() && x.Id != entity.Id, "规则编码已存在");
        entity.Code = req.Code.Trim();
        entity.Name = req.Name.Trim();
        entity.TriggerType = WmsTransportTriggerTypes.ParseOr(req.TriggerType);
        entity.Enabled = req.Enabled;
        entity.Priority = req.Priority;
        entity.SourceSelectorJson = TransportSelectorParser.NormalizeSelectorJson(req.SourceSelectorJson);
        entity.TargetSelectorJson = TransportSelectorParser.NormalizeSelectorJson(req.TargetSelectorJson);
        entity.TaskOptionsJson = TransportSelectorParser.NormalizeTaskOptionsJson(req.TaskOptionsJson);
        ApplyCommon(entity, req, actor);
        await _uow.SaveChangesAsync();
        return entity;
    }

    public async Task DeleteAsync(Guid id, long? version, string actor)
    {
        await _rules.SoftDeleteAsync(id, version);
        await _uow.SaveChangesAsync();
    }

    private static void StampCreate(EntityBase entity, string actor)
    {
        entity.CreatedBy = actor;
        entity.UpdatedBy = actor;
    }

    private static void ApplyCommon(EntityBase entity, CommonRequest req, string actor)
    {
        entity.IsLock = req.IsLock;
        entity.Remark = req.Remark.TrimOr("");
        entity.Extend = NormalizeExtend(req.Extend);
        entity.UpdatedBy = actor;
    }

    private static string NormalizeExtend(string? extend)
    {
        if (string.IsNullOrWhiteSpace(extend)) return "{}";
        if (extend.Length > 4000) throw new InvalidOperationException("扩展字段过长");
        return extend;
    }
}

public sealed record TransportRuleRequest(
    Guid? Id,
    long? Version,
    string Code,
    string Name,
    string TriggerType,
    bool Enabled,
    int Priority,
    string SourceSelectorJson,
    string TargetSelectorJson,
    string TaskOptionsJson,
    bool IsLock,
    string Remark,
    string Extend) : CommonRequest(Id, Version, IsLock, Remark, Extend);
