' ============================================================
' Module Name: Master_244
' Module Desc: T1 master data management (244)
' Module Methods:
'   - Worksheet_Change
'   - Validate
' ============================================================

' ============================================================
' Event Handlers
' ============================================================
Private Sub Worksheet_Change(ByVal Target As Range)
    Dim HasHeaderEdit As Boolean: HasHeaderEdit = CheckHeaderEdit(Me, Target)
    If HasHeaderEdit = True Then Exit Sub

    Application.EnableEvents = False
    On Error GoTo Finally

    ' === Column C changes: Create D column dropdown ===
    If Target.Column = 3 And Target.Row >= 7 Then
        Dim cell As Range
        For Each cell In Target
            If Trim(cell.Value) = "" Then
                Call ClearDataRow(Me, cell.Row)
            Else
                Call BuildDisplayDropdown(Me, cell.Row)
            End If
        Next
    End If

    ' === Column G changes: Fill E column ===
    If Target.Column = 7 And Target.Row >= 7 Then
        Dim cellG As Range
        For Each cellG In Target
            Dim displayValue As String: displayValue = Trim(cellG.Value)
            If displayValue <> "" Then
                cellG.Value = GetCode(displayValue)
            End If
        Next
    End If

    Application.EnableEvents = True
    Exit Sub

Finally:
    HandleError "Worksheet_Change"
    Application.EnableEvents = True
End Sub

' Prevent insert/delete row in header area
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
    Dim sheetConfDict As Object: Set sheetConfDict = GetSheetConfig()
    Dim sheetConf As Object: Set sheetConf = sheetConfDict(Me.CodeName)
    Dim filterRow As Long: filterRow = sheetConf("FilterRow")

    If Target.Row < filterRow + 1 Then
        Cancel = True
        MsgBox "Cannot insert or delete row in header area.", vbExclamation
    End If
End Sub

'
Public Sub Validate(ws As Worksheet, ByVal rowNum As Long, ByVal lastDataRow As Long)
    On Error GoTo ErrHandler

    ' Build engine: same order as original Validate
    Dim engine As ValidationRuleEngine: Set engine = New ValidationRuleEngine
    With engine
        .AddRequired "C"          ' C: required
        .AddChar "C", 3           ' C: exact 3 chars
        .AddAlphanumeric "C"      ' C: alphanumeric only
        .AddDuplicate "C"         ' C: no duplicate in prior rows
        .AddRequired "D"          ' D: required
        .AddVarchar "D", 80       ' D: max 80 chars
        .AddVarchar "E", 80       ' E: max 80 chars
        .AddVarchar "F", 80       ' F: max 80 chars
        .AddCheck01 "G"           ' G: 0 or 1 only
    End With

    Call engine.ValidateRow(ws, rowNum, lastDataRow)

    Exit Sub

ErrHandler:
    SetLastErrorMsg Err.Description
End Sub