@page "/admin/ldap-mappings"
@attribute [Authorize(Policy = AuthorizationPolicies.RequireAdmin)]
@using ScadaLink.Commons.Entities.Security
@using ScadaLink.Commons.Interfaces.Repositories
@using ScadaLink.Security
@inject ISecurityRepository SecurityRepository
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h4 class="mb-0">LDAP Group Mappings</h4>
        <button class="btn btn-primary btn-sm" @onclick='() => NavigationManager.NavigateTo("/admin/ldap-mappings/create")'>Add Mapping</button>
    </div>

    @if (_loading)
    {
        <p class="text-muted">Loading...</p>
    }
    else if (_errorMessage != null)
    {
        <div class="alert alert-danger">@_errorMessage</div>
    }
    else
    {
        @* Mappings table *@
        <table class="table table-sm table-striped table-hover">
            <thead class="table-dark">
                <tr>
                    <th>ID</th>
                    <th>LDAP Group Name</th>
                    <th>Role</th>
                    <th>Site Scope Rules</th>
                    <th style="width: 200px;">Actions</th>
                </tr>
            </thead>
            <tbody>
                @if (_mappings.Count == 0)
                {
                    <tr>
                        <td colspan="5" class="text-muted text-center">No mappings configured.</td>
                    </tr>
                }
                @foreach (var mapping in _mappings)
                {
                    <tr>
                        <td>@mapping.Id</td>
                        <td>@mapping.LdapGroupName</td>
                        <td><span class="badge bg-secondary">@mapping.Role</span></td>
                        <td>
                            @{
                                var rules = _scopeRules.GetValueOrDefault(mapping.Id);
                            }
                            @if (rules != null && rules.Count > 0)
                            {
                                @foreach (var rule in rules)
                                {
                                    <span class="badge bg-info text-dark me-1">Site @rule.SiteId</span>
                                }
                            }
                            else
                            {
                                <span class="text-muted small">All sites</span>
                            }
                            @if (mapping.Role.Equals("Deployment", StringComparison.OrdinalIgnoreCase))
                            {
                                <span class="text-muted small ms-2">(manage on edit page)</span>
                            }
                        </td>
                        <td>
                            <button class="btn btn-outline-primary btn-sm py-0 px-1 me-1"
                                    @onclick='() => NavigationManager.NavigateTo($"/admin/ldap-mappings/{mapping.Id}/edit")'>Edit</button>
                            <button class="btn btn-outline-danger btn-sm py-0 px-1"
                                    @onclick="() => DeleteMapping(mapping.Id)">Delete</button>
                        </td>
                    </tr>
                }
            </tbody>
        </table>

    }
</div>

@code {
    private List<LdapGroupMapping> _mappings = new();
    private Dictionary<int, List<SiteScopeRule>> _scopeRules = new();
    private bool _loading = true;
    private string? _errorMessage;

    protected override async Task OnInitializedAsync()
    {
        await LoadDataAsync();
    }

    private async Task LoadDataAsync()
    {
        _loading = true;
        _errorMessage = null;
        try
        {
            _mappings = (await SecurityRepository.GetAllMappingsAsync()).ToList();
            _scopeRules.Clear();
            foreach (var mapping in _mappings)
            {
                var rules = await SecurityRepository.GetScopeRulesForMappingAsync(mapping.Id);
                if (rules.Count > 0)
                {
                    _scopeRules[mapping.Id] = rules.ToList();
                }
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"Failed to load mappings: {ex.Message}";
        }
        _loading = false;
    }

    private async Task DeleteMapping(int id)
    {
        try
        {
            // Also delete scope rules for this mapping
            var rules = await SecurityRepository.GetScopeRulesForMappingAsync(id);
            foreach (var rule in rules)
            {
                await SecurityRepository.DeleteScopeRuleAsync(rule.Id);
            }
            await SecurityRepository.DeleteMappingAsync(id);
            await SecurityRepository.SaveChangesAsync();
            await LoadDataAsync();
        }
        catch (Exception ex)
        {
            _errorMessage = $"Delete failed: {ex.Message}";
        }
    }

}
