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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OptimAI.BRE.RuleEngine.Api;
using OptimAI.BRE.Shared.Domain;

namespace OptimAI.BRE.RuleDesigner.Api;

[ApiController]
[Route("api/v1/rules")]
[Authorize]
public sealed class RuleDesignerController : ControllerBase
{
    private readonly IRuleRepository _ruleRepo;
    private readonly IRuleVersionRepository _versionRepo;
    private readonly IRuleApprovalService _approvalService;
    private readonly IAuditService _auditService;
    private readonly ITenantContextAccessor _tenantAccessor;

    public RuleDesignerController(
        IRuleRepository ruleRepo,
        IRuleVersionRepository versionRepo,
        IRuleApprovalService approvalService,
        IAuditService auditService,
        ITenantContextAccessor tenantAccessor)
    {
        _ruleRepo = ruleRepo;
        _versionRepo = versionRepo;
        _approvalService = approvalService;
        _auditService = auditService;
        _tenantAccessor = tenantAccessor;
    }

    [HttpGet]
    [ProducesResponseType(typeof(PagedResponse<RuleSummaryDto>), 200)]
    public async Task<IActionResult> GetRules(
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 20,
        [FromQuery] string? category = null,
        [FromQuery] string? ruleType = null,
        [FromQuery] string? status = null,
        [FromQuery] string? search = null,
        CancellationToken ct = default)
    {
        var result = await _ruleRepo.GetPagedAsync(new RuleQuery
        {
            TenantId = _tenantAccessor.TenantId,
            Page = page,
            PageSize = Math.Min(pageSize, 100),
            Category = category,
            RuleType = ruleType,
            Status = status,
            Search = search
        }, ct);

        return Ok(result);
    }

    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(RuleDetailDto), 200)]
    [ProducesResponseType(404)]
    public async Task<IActionResult> GetRule(Guid id, CancellationToken ct)
    {
        var rule = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (rule == null) return NotFound();
        return Ok(MapToDetailDto(rule));
    }

    [HttpPost]
    [Authorize(Policy = "RuleWrite")]
    [ProducesResponseType(typeof(RuleDetailDto), 201)]
    public async Task<IActionResult> CreateRule([FromBody] CreateRuleRequest request, CancellationToken ct)
    {
        var rule = new Rule
        {
            TenantId = _tenantAccessor.TenantId,
            RuleCode = request.RuleCode ?? GenerateRuleCode(request.RuleName),
            RuleName = request.RuleName,
            Description = request.Description,
            CategoryId = request.CategoryId,
            RuleType = Enum.Parse<RuleType>(request.RuleType, true),
            Priority = request.Priority,
            Tags = request.Tags ?? new(),
            Status = RuleStatus.Draft,
            CreatedBy = _tenantAccessor.UserId
        };

        var version = new RuleVersion
        {
            TenantId = _tenantAccessor.TenantId,
            VersionNumber = 1,
            VersionLabel = "v1.0",
            RuleDefinition = request.RuleDefinition,
            Status = RuleStatus.Draft,
            IsCurrent = true,
            CreatedBy = _tenantAccessor.UserId
        };

        var created = await _ruleRepo.CreateWithVersionAsync(rule, version, ct);

        await _auditService.LogAsync(new AuditLog
        {
            TenantId = _tenantAccessor.TenantId,
            UserId = _tenantAccessor.UserId,
            Action = "RULE_CREATED",
            EntityType = "RULE",
            EntityId = created.Id.ToString(),
            NewValues = new Dictionary<string, object> { ["ruleCode"] = created.RuleCode, ["ruleName"] = created.RuleName }
        }, ct);

        return CreatedAtAction(nameof(GetRule), new { id = created.Id }, MapToDetailDto(created));
    }

    [HttpPut("{id:guid}")]
    [Authorize(Policy = "RuleWrite")]
    [ProducesResponseType(typeof(RuleDetailDto), 200)]
    [ProducesResponseType(404)]
    public async Task<IActionResult> UpdateRule(Guid id, [FromBody] UpdateRuleRequest request, CancellationToken ct)
    {
        var rule = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (rule == null) return NotFound();

        var oldValues = new Dictionary<string, object> { ["ruleName"] = rule.RuleName, ["status"] = rule.Status.ToString() };

        // Create new version
        var latestVersion = await _versionRepo.GetLatestAsync(id, ct);
        var newVersionNumber = (latestVersion?.VersionNumber ?? 0) + 1;

        var newVersion = new RuleVersion
        {
            TenantId = _tenantAccessor.TenantId,
            RuleId = id,
            VersionNumber = newVersionNumber,
            VersionLabel = $"v{newVersionNumber}.0",
            RuleDefinition = request.RuleDefinition,
            ChangeSummary = request.ChangeSummary,
            Status = RuleStatus.Draft,
            IsCurrent = false,
            CreatedBy = _tenantAccessor.UserId
        };

        rule.RuleName = request.RuleName ?? rule.RuleName;
        rule.Description = request.Description ?? rule.Description;
        rule.Priority = request.Priority ?? rule.Priority;
        rule.Tags = request.Tags ?? rule.Tags;
        rule.Status = RuleStatus.Draft;
        rule.IsPublished = false;

        await _ruleRepo.UpdateWithNewVersionAsync(rule, newVersion, ct);

        await _auditService.LogAsync(new AuditLog
        {
            TenantId = _tenantAccessor.TenantId,
            UserId = _tenantAccessor.UserId,
            Action = "RULE_UPDATED",
            EntityType = "RULE",
            EntityId = id.ToString(),
            OldValues = oldValues,
            NewValues = new Dictionary<string, object>
            {
                ["ruleName"] = rule.RuleName,
                ["versionNumber"] = newVersionNumber,
                ["changeSummary"] = request.ChangeSummary ?? ""
            }
        }, ct);

        var updated = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        return Ok(MapToDetailDto(updated!));
    }

    [HttpPost("{id:guid}/submit-for-approval")]
    [Authorize(Policy = "RuleWrite")]
    public async Task<IActionResult> SubmitForApproval(Guid id, [FromBody] SubmitApprovalRequest request, CancellationToken ct)
    {
        var rule = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (rule == null) return NotFound();

        await _approvalService.SubmitForApprovalAsync(id, rule.CurrentVersionId!.Value, _tenantAccessor.TenantId, _tenantAccessor.UserId, request.Comments, ct);

        return Ok(new { message = "Rule submitted for approval", status = "PENDING_APPROVAL" });
    }

    [HttpPost("{id:guid}/approve")]
    [Authorize(Policy = "RuleApprove")]
    public async Task<IActionResult> ApproveRule(Guid id, [FromBody] ApproveRuleRequest request, CancellationToken ct)
    {
        await _approvalService.ApproveAsync(id, _tenantAccessor.TenantId, _tenantAccessor.UserId, request.Comments, ct);

        await _auditService.LogAsync(new AuditLog
        {
            TenantId = _tenantAccessor.TenantId,
            UserId = _tenantAccessor.UserId,
            Action = "RULE_APPROVED",
            EntityType = "RULE",
            EntityId = id.ToString()
        }, ct);

        return Ok(new { message = "Rule approved successfully" });
    }

    [HttpPost("{id:guid}/reject")]
    [Authorize(Policy = "RuleApprove")]
    public async Task<IActionResult> RejectRule(Guid id, [FromBody] RejectRuleRequest request, CancellationToken ct)
    {
        await _approvalService.RejectAsync(id, _tenantAccessor.TenantId, _tenantAccessor.UserId, request.Comments, ct);
        return Ok(new { message = "Rule rejected" });
    }

    [HttpPost("{id:guid}/publish")]
    [Authorize(Policy = "RulePublish")]
    public async Task<IActionResult> PublishRule(Guid id, CancellationToken ct)
    {
        var rule = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (rule == null) return NotFound();
        if (rule.Status != RuleStatus.Approved) return BadRequest(new { error = "Rule must be approved before publishing" });

        await _ruleRepo.PublishAsync(id, _tenantAccessor.TenantId, _tenantAccessor.UserId, ct);

        await _auditService.LogAsync(new AuditLog
        {
            TenantId = _tenantAccessor.TenantId,
            UserId = _tenantAccessor.UserId,
            Action = "RULE_PUBLISHED",
            EntityType = "RULE",
            EntityId = id.ToString()
        }, ct);

        return Ok(new { message = "Rule published to production" });
    }

    [HttpPost("{id:guid}/clone")]
    [Authorize(Policy = "RuleWrite")]
    public async Task<IActionResult> CloneRule(Guid id, [FromBody] CloneRuleRequest request, CancellationToken ct)
    {
        var original = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (original == null) return NotFound();

        var cloned = await _ruleRepo.CloneAsync(id, _tenantAccessor.TenantId, _tenantAccessor.UserId, request.NewRuleCode, request.NewRuleName, ct);

        return CreatedAtAction(nameof(GetRule), new { id = cloned.Id }, MapToDetailDto(cloned));
    }

    [HttpPatch("{id:guid}/toggle")]
    [Authorize(Policy = "RuleWrite")]
    public async Task<IActionResult> ToggleRule(Guid id, CancellationToken ct)
    {
        var rule = await _ruleRepo.GetByIdAsync(id, _tenantAccessor.TenantId, ct);
        if (rule == null) return NotFound();

        await _ruleRepo.ToggleActiveAsync(id, _tenantAccessor.TenantId, ct);
        return Ok(new { message = $"Rule {(rule.IsActive ? "disabled" : "enabled")}", isActive = !rule.IsActive });
    }

    [HttpGet("{id:guid}/versions")]
    [ProducesResponseType(typeof(List<RuleVersionSummaryDto>), 200)]
    public async Task<IActionResult> GetVersions(Guid id, CancellationToken ct)
    {
        var versions = await _versionRepo.GetAllAsync(id, _tenantAccessor.TenantId, ct);
        return Ok(versions.Select(v => new RuleVersionSummaryDto
        {
            Id = v.Id,
            VersionNumber = v.VersionNumber,
            VersionLabel = v.VersionLabel ?? $"v{v.VersionNumber}.0",
            Status = v.Status.ToString(),
            ChangeSummary = v.ChangeSummary,
            IsCurrent = v.IsCurrent,
            CreatedAt = v.CreatedAt,
            ApprovedAt = v.ApprovedAt,
            PublishedAt = v.PublishedAt
        }).ToList());
    }

    [HttpPut("{id:guid}/scopes")]
    [Authorize(Policy = "RuleWrite")]
    public async Task<IActionResult> UpdateScopes(Guid id, [FromBody] UpdateScopesRequest request, CancellationToken ct)
    {
        await _ruleRepo.UpdateScopesAsync(id, _tenantAccessor.TenantId, request.Scopes, ct);
        return Ok(new { message = "Rule scopes updated" });
    }

    private static string GenerateRuleCode(string ruleName)
    {
        return ruleName.ToLower()
            .Replace(" ", "_")
            .Replace("-", "_")
            .Replace("/", "_")
            [..Math.Min(ruleName.Length, 80)];
    }

    private static RuleDetailDto MapToDetailDto(Rule rule) => new()
    {
        Id = rule.Id,
        RuleCode = rule.RuleCode,
        RuleName = rule.RuleName,
        Description = rule.Description,
        CategoryId = rule.CategoryId,
        RuleType = rule.RuleType.ToString(),
        Priority = rule.Priority,
        IsActive = rule.IsActive,
        IsPublished = rule.IsPublished,
        Status = rule.Status.ToString(),
        Tags = rule.Tags,
        CurrentVersion = rule.CurrentVersion != null ? new RuleVersionDto
        {
            Id = rule.CurrentVersion.Id,
            VersionNumber = rule.CurrentVersion.VersionNumber,
            VersionLabel = rule.CurrentVersion.VersionLabel ?? $"v{rule.CurrentVersion.VersionNumber}.0",
            RuleDefinition = rule.CurrentVersion.RuleDefinition,
            Status = rule.CurrentVersion.Status.ToString(),
            CreatedAt = rule.CurrentVersion.CreatedAt
        } : null,
        Scopes = rule.Scopes.Select(s => new RuleScopeDto
        {
            ScopeType = s.ScopeType.ToString(),
            ScopeValue = s.ScopeValue,
            IsExcluded = s.IsExcluded
        }).ToList(),
        CreatedAt = rule.CreatedAt,
        UpdatedAt = rule.UpdatedAt
    };
}

// ============================================================
// DTOs
// ============================================================

public record RuleSummaryDto
{
    public Guid Id { get; init; }
    public string RuleCode { get; init; } = default!;
    public string RuleName { get; init; } = default!;
    public string RuleType { get; init; } = default!;
    public string Status { get; init; } = default!;
    public bool IsActive { get; init; }
    public bool IsPublished { get; init; }
    public int Priority { get; init; }
    public List<string> Tags { get; init; } = new();
    public int VersionCount { get; init; }
    public DateTime CreatedAt { get; init; }
    public DateTime UpdatedAt { get; init; }
}

public record RuleDetailDto : RuleSummaryDto
{
    public string? Description { get; init; }
    public Guid? CategoryId { get; init; }
    public RuleVersionDto? CurrentVersion { get; init; }
    public List<RuleScopeDto> Scopes { get; init; } = new();
}

public record RuleVersionDto
{
    public Guid Id { get; init; }
    public int VersionNumber { get; init; }
    public string VersionLabel { get; init; } = default!;
    public RuleDefinition RuleDefinition { get; init; } = default!;
    public string Status { get; init; } = default!;
    public DateTime CreatedAt { get; init; }
}

public record RuleVersionSummaryDto
{
    public Guid Id { get; init; }
    public int VersionNumber { get; init; }
    public string VersionLabel { get; init; } = default!;
    public string Status { get; init; } = default!;
    public string? ChangeSummary { get; init; }
    public bool IsCurrent { get; init; }
    public DateTime CreatedAt { get; init; }
    public DateTime? ApprovedAt { get; init; }
    public DateTime? PublishedAt { get; init; }
}

public record RuleScopeDto
{
    public string ScopeType { get; init; } = default!;
    public string ScopeValue { get; init; } = default!;
    public bool IsExcluded { get; init; }
}

public record CreateRuleRequest
{
    public string RuleName { get; init; } = default!;
    public string? RuleCode { get; init; }
    public string? Description { get; init; }
    public Guid? CategoryId { get; init; }
    public string RuleType { get; init; } = default!;
    public int Priority { get; init; } = 100;
    public List<string>? Tags { get; init; }
    public RuleDefinition RuleDefinition { get; init; } = default!;
}

public record UpdateRuleRequest
{
    public string? RuleName { get; init; }
    public string? Description { get; init; }
    public int? Priority { get; init; }
    public List<string>? Tags { get; init; }
    public string? ChangeSummary { get; init; }
    public RuleDefinition RuleDefinition { get; init; } = default!;
}

public record SubmitApprovalRequest { public string? Comments { get; init; } }
public record ApproveRuleRequest { public string? Comments { get; init; } }
public record RejectRuleRequest { public string Comments { get; init; } = default!; }
public record CloneRuleRequest { public string? NewRuleCode { get; init; } public string? NewRuleName { get; init; } }

public record UpdateScopesRequest
{
    public List<RuleScopeRequest> Scopes { get; init; } = new();
}

public record RuleScopeRequest
{
    public string ScopeType { get; init; } = default!;
    public string ScopeValue { get; init; } = default!;
    public bool IsExcluded { get; init; }
}

public record RuleQuery
{
    public Guid TenantId { get; init; }
    public int Page { get; init; } = 1;
    public int PageSize { get; init; } = 20;
    public string? Category { get; init; }
    public string? RuleType { get; init; }
    public string? Status { get; init; }
    public string? Search { get; init; }
}

public interface IRuleRepository
{
    Task<PagedResponse<RuleSummaryDto>> GetPagedAsync(RuleQuery query, CancellationToken ct = default);
    Task<Rule?> GetByIdAsync(Guid id, Guid tenantId, CancellationToken ct = default);
    Task<Rule> CreateWithVersionAsync(Rule rule, RuleVersion version, CancellationToken ct = default);
    Task UpdateWithNewVersionAsync(Rule rule, RuleVersion newVersion, CancellationToken ct = default);
    Task PublishAsync(Guid id, Guid tenantId, Guid publishedBy, CancellationToken ct = default);
    Task<Rule> CloneAsync(Guid id, Guid tenantId, Guid clonedBy, string? newCode, string? newName, CancellationToken ct = default);
    Task ToggleActiveAsync(Guid id, Guid tenantId, CancellationToken ct = default);
    Task UpdateScopesAsync(Guid id, Guid tenantId, List<RuleScopeRequest> scopes, CancellationToken ct = default);
}

public interface IRuleVersionRepository
{
    Task<RuleVersion?> GetLatestAsync(Guid ruleId, CancellationToken ct = default);
    Task<List<RuleVersion>> GetAllAsync(Guid ruleId, Guid tenantId, CancellationToken ct = default);
}

public interface IRuleApprovalService
{
    Task SubmitForApprovalAsync(Guid ruleId, Guid versionId, Guid tenantId, Guid requestedBy, string? comments, CancellationToken ct = default);
    Task ApproveAsync(Guid ruleId, Guid tenantId, Guid approvedBy, string? comments, CancellationToken ct = default);
    Task RejectAsync(Guid ruleId, Guid tenantId, Guid rejectedBy, string comments, CancellationToken ct = default);
}

public interface IAuditService
{
    Task LogAsync(AuditLog log, CancellationToken ct = default);
}