@page "/deployment/instances/create"
@using ZB.MOM.WW.ScadaBridge.Security
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Instances
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites
@using ZB.MOM.WW.ScadaBridge.Commons.Entities.Templates
@using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories
@using ZB.MOM.WW.ScadaBridge.TemplateEngine.Services
@attribute [Authorize(Policy = AuthorizationPolicies.RequireDeployment)]
@inject ITemplateEngineRepository TemplateEngineRepository
@inject ISiteRepository SiteRepository
@inject ZB.MOM.WW.ScadaBridge.CentralUI.Auth.SiteScopeService SiteScope
@inject InstanceService InstanceService
@inject AuthenticationStateProvider AuthStateProvider
@inject NavigationManager NavigationManager

<div class="container-fluid mt-3">
    <div class="d-flex align-items-center mb-3">
        <a href="/deployment/topology" class="btn btn-outline-secondary btn-sm me-3">&larr; Back</a>
        <h4 class="mb-0">Create Instance</h4>
    </div>

    @if (_loading)
    {
        <LoadingSpinner IsLoading="true" />
    }
    else
    {
        <div class="card mb-3">
            <div class="card-body">
                <div class="mb-2">
                    <label class="form-label small">Instance Name</label>
                    <input type="text" class="form-control form-control-sm" @bind="_createName" placeholder="e.g. Motor-1" />
                </div>
                <div class="mb-2">
                    <label class="form-label small">Template</label>
                    <select class="form-select form-select-sm" @bind="_createTemplateId">
                        <option value="0">Select template...</option>
                        @foreach (var t in _templates)
                        {
                            <option value="@t.Id">@t.Name</option>
                        }
                    </select>
                </div>
                <div class="mb-2">
                    <label class="form-label small">Site</label>
                    <select class="form-select form-select-sm" @bind="_createSiteId">
                        <option value="0">Select site...</option>
                        @foreach (var s in _sites)
                        {
                            <option value="@s.Id">@s.Name</option>
                        }
                    </select>
                </div>
                <div class="mb-2">
                    <label class="form-label small">Area</label>
                    <select class="form-select form-select-sm" @bind="_createAreaId">
                        <option value="0">No area</option>
                        @foreach (var a in _allAreas.Where(a => a.SiteId == _createSiteId))
                        {
                            <option value="@a.Id">@a.Name</option>
                        }
                    </select>
                </div>
                @if (_formError != null)
                {
                    <div class="text-danger small mt-2">@_formError</div>
                }
                <div class="mt-3">
                    <button class="btn btn-success btn-sm me-1" @onclick="CreateInstance">Create</button>
                    <button class="btn btn-outline-secondary btn-sm" @onclick="GoBack">Cancel</button>
                </div>
            </div>
        </div>
    }
</div>

@code {
    [SupplyParameterFromQuery] public int? SiteId { get; set; }
    [SupplyParameterFromQuery] public int? AreaId { get; set; }

    private List<Site> _sites = new();
    private List<Template> _templates = new();
    private List<Area> _allAreas = new();
    private bool _loading = true;

    private string _createName = string.Empty;
    private int _createTemplateId;
    private int _createSiteId;
    private int _createAreaId;
    private string? _formError;

    protected override async Task OnInitializedAsync()
    {
        try
        {
            _templates = (await TemplateEngineRepository.GetAllTemplatesAsync()).ToList();
            // Site scoping (CentralUI-002): a scoped Deployment user may only
            // create instances on sites they are permitted on.
            _sites = await SiteScope.FilterSitesAsync(await SiteRepository.GetAllSitesAsync());

            _allAreas.Clear();
            foreach (var site in _sites)
            {
                var areas = await TemplateEngineRepository.GetAreasBySiteIdAsync(site.Id);
                _allAreas.AddRange(areas);
            }

            if (SiteId is int sid && _sites.Any(s => s.Id == sid))
            {
                _createSiteId = sid;
            }
            if (AreaId is int aid && _allAreas.Any(a => a.Id == aid && a.SiteId == _createSiteId))
            {
                _createAreaId = aid;
            }
        }
        catch (Exception ex)
        {
            _formError = $"Failed to load data: {ex.Message}";
        }
        _loading = false;
    }

    private async Task CreateInstance()
    {
        _formError = null;
        if (string.IsNullOrWhiteSpace(_createName)) { _formError = "Instance name is required."; return; }
        if (_createTemplateId == 0) { _formError = "Select a template."; return; }
        if (_createSiteId == 0) { _formError = "Select a site."; return; }
        // Site scoping (CentralUI-002): re-check server-side before the mutating
        // command, independent of what the site dropdown was populated with.
        if (!await SiteScope.IsSiteAllowedAsync(_createSiteId))
        {
            _formError = "You are not permitted to create instances on the selected site.";
            return;
        }

        try
        {
            var user = await GetCurrentUserAsync();
            var result = await InstanceService.CreateInstanceAsync(
                _createName.Trim(), _createTemplateId, _createSiteId, _createAreaId == 0 ? null : _createAreaId, user);
            if (result.IsSuccess)
            {
                NavigationManager.NavigateTo("/deployment/topology");
            }
            else
            {
                _formError = result.Error;
            }
        }
        catch (Exception ex)
        {
            _formError = $"Create failed: {ex.Message}";
        }
    }

    private void GoBack() => NavigationManager.NavigateTo("/deployment/topology");

    // CentralUI-024: delegates to the shared helper so the claim type stays
    // resolved through JwtTokenService rather than a duplicated magic string.
    private Task<string> GetCurrentUserAsync()
        => AuthStateProvider.GetCurrentUsernameAsync();
}
