using SolutionErp.Domain.Common;
using SolutionErp.Domain.Identity;     // reuse PositionLevel

namespace SolutionErp.Domain.Contracts;

// Versioned workflow definition per ContractType. Admin can edit quy trình =>
// creates a NEW version; old version stays for contracts already pinned to it.
//
// Invariant: for any ContractType, AT MOST ONE WorkflowDefinition has
// IsActive=true at any given time. Contract.WorkflowDefinitionId pins the
// contract to its chosen version at creation time — so changing the active
// version does not retroactively affect running contracts.
public class WorkflowDefinition : BaseEntity
{
    public string Code { get; set; } = string.Empty;            // "QT-TP-NCC" admin-editable
    public int Version { get; set; }                            // monotonically increases per Code
    public ContractType ContractType { get; set; }
    public string Name { get; set; } = string.Empty;            // display label
    public string? Description { get; set; }
    public bool IsActive { get; set; }                          // only one per ContractType
    public DateTime? ActivatedAt { get; set; }

    public List<WorkflowStep> Steps { get; set; } = new();
}

// Workflow Step (Session 16 — Mig 21 drastic refactor):
// Mỗi step = 1 (Phòng × Cấp + Approvers users). Sequential per Order.
// Service iterate steps OrderBy(Order), advance Contract.CurrentWorkflowStepIndex
// per approve. Phase column deprecated post-Mig 21 (set ChoDuyet=10 cho new
// definitions, giữ giá trị cũ cho backward compat data).
public class WorkflowStep : BaseEntity
{
    public Guid WorkflowDefinitionId { get; set; }
    public int Order { get; set; }                              // 1-based sequence
    public ContractPhase Phase { get; set; }                    // [DEPRECATED post-Mig 21] dùng ChoDuyet=10 cho new
    public string Name { get; set; } = string.Empty;            // display "Phòng A — Cấp 1"
    public int? SlaDays { get; set; }                           // null = no SLA

    // Mig 21 — Phòng × Cấp (flat workflow). Approver match: actor.DepartmentId
    // == step.DepartmentId AND actor.PositionLevel == step.PositionLevel
    // (OR-of-many cùng cấp+phòng). Bypass: actor.PositionLevel cao hơn cùng dept
    // + CanBypassReview → skip cấp dưới.
    public Guid? DepartmentId { get; set; }
    public PositionLevel? PositionLevel { get; set; }

    public WorkflowDefinition? WorkflowDefinition { get; set; }
    public List<WorkflowStepApprover> Approvers { get; set; } = new();
}

public enum WorkflowApproverKind
{
    Role = 1,  // AssignmentValue = role name (AppRoles.*)
    User = 2,  // AssignmentValue = user id (Guid as string)
}

public class WorkflowStepApprover : BaseEntity
{
    public Guid WorkflowStepId { get; set; }
    public WorkflowApproverKind Kind { get; set; }
    public string AssignmentValue { get; set; } = string.Empty;

    public WorkflowStep? Step { get; set; }
}
