using SolutionErp.Domain.Identity;

namespace SolutionErp.Domain.Budgets;

// Policy hardcoded đơn giản — chưa versioned (theo user "tạm thời simple
// default"). Tương lai nếu admin cần config qua UI: thêm BudgetWorkflow
// Definition tables tương tự PE workflow.
public sealed record BudgetPolicy(
    string Name,
    string Description,
    IReadOnlyDictionary<(BudgetPhase From, BudgetPhase To), string[]> Transitions,
    IReadOnlyDictionary<BudgetPhase, TimeSpan?> PhaseSla,
    IReadOnlyList<BudgetPhase> ActivePhases)
{
    public bool HasPhase(BudgetPhase phase) => ActivePhases.Contains(phase);

    public bool IsTransitionAllowed(
        BudgetPhase from, BudgetPhase to,
        IReadOnlyList<string> actorRoles)
    {
        if (!Transitions.TryGetValue((from, to), out var roles)) return false;
        return actorRoles.Any(r => roles.Contains(r));
    }

    public IReadOnlyList<BudgetPhase> NextPhasesFrom(BudgetPhase from) =>
        Transitions.Keys.Where(k => k.From == from).Select(k => k.To).Distinct().ToList();
}

public static class BudgetPolicies
{
    private static readonly Dictionary<BudgetPhase, TimeSpan?> DefaultSla = new()
    {
        [BudgetPhase.DangSoanThao] = TimeSpan.FromDays(5),
        [BudgetPhase.ChoCCM] = TimeSpan.FromDays(3),
        [BudgetPhase.ChoCEO] = TimeSpan.FromDays(2),
        [BudgetPhase.DaDuyet] = null,
        [BudgetPhase.TuChoi] = null,
    };

    public static readonly BudgetPolicy Default = new(
        Name: "Default",
        Description: "Quy trình ngân sách 3-step (Drafter → CCM → CEO).",
        Transitions: new Dictionary<(BudgetPhase, BudgetPhase), string[]>
        {
            [(BudgetPhase.DangSoanThao, BudgetPhase.ChoCCM)] = [AppRoles.Drafter, AppRoles.DeptManager],
            [(BudgetPhase.DangSoanThao, BudgetPhase.TuChoi)] = [AppRoles.Drafter, AppRoles.DeptManager],

            [(BudgetPhase.ChoCCM, BudgetPhase.ChoCEO)] = [AppRoles.CostControl],
            [(BudgetPhase.ChoCCM, BudgetPhase.DangSoanThao)] = [AppRoles.CostControl],

            [(BudgetPhase.ChoCEO, BudgetPhase.DaDuyet)] = [AppRoles.Director, AppRoles.AuthorizedSigner],
            [(BudgetPhase.ChoCEO, BudgetPhase.DangSoanThao)] = [AppRoles.Director, AppRoles.AuthorizedSigner],
        },
        PhaseSla: DefaultSla,
        ActivePhases:
        [
            BudgetPhase.DangSoanThao,
            BudgetPhase.ChoCCM,
            BudgetPhase.ChoCEO,
            BudgetPhase.DaDuyet,
            BudgetPhase.TuChoi,
        ]);
}
