@page "/scripts/new"
@page "/scripts/{ScriptId}"
@* Script CRUD. SourceHash is computed automatically from SourceCode on save so the
   integrity check in v2's deployment pipeline doesn't require operator action. *@
@attribute [Authorize(Policy = AdminUiPolicies.ConfigEditor)]
@rendermode RenderMode.InteractiveServer
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.EntityFrameworkCore
@using System.ComponentModel.DataAnnotations
@using System.Security.Cryptography
@using System.Text
@using ZB.MOM.WW.OtOpcUa.Configuration
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
@using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis
@inject IDbContextFactory<OtOpcUaConfigDbContext> DbFactory
@inject NavigationManager Nav

<PageErrorBoundary>
<PageTitle>Script editor · OtOpcUa</PageTitle>
<div class="page-head">
    <h1>@(IsNew ? "New script" : "Edit script")</h1>
    <span class="spacer"></span>
    <a href="/scripts" class="btn btn-outline-secondary btn-sm">Cancel</a>
</div>

@if (!_loaded)
{
    <p>Loading…</p>
}
else if (!IsNew && _existing is null)
{
    <section class="panel notice rise"><span class="mono">@ScriptId</span> not found.</section>
}
else
{
    @* OnSubmit (not OnValidSubmit): the editor text is pulled from Monaco FIRST, then validated — the bound
       SourceCode is only refreshed at blur, so validating before the pull could judge stale text. *@
    <EditForm Model="_form" OnSubmit="SubmitAsync" FormName="scriptEdit">
        <DataAnnotationsValidator />
        <ValidationSummary class="alert alert-danger py-2 px-3" />
        <section class="panel rise">
            <h2 class="panel-head">Identity</h2>
            <div style="padding:1rem">
                <div class="row">
                    @* ScriptId is system-generated (SC-…) on create, never operator-supplied —
                       shown read-only when editing an existing script, hidden on the New page. *@
                    @if (!IsNew)
                    {
                        <div class="col-md-5 mb-3">
                            <label class="form-label">ScriptId</label>
                            <input value="@_form.ScriptId" disabled class="form-control form-control-sm mono" />
                        </div>
                    }
                    <div class="@(IsNew ? "col-md-12" : "col-md-7") mb-3">
                        <label class="form-label">Name</label>
                        <InputText @bind-Value="_form.Name" class="form-control form-control-sm" />
                    </div>
                </div>
            </div>
        </section>

        <section class="panel rise mt-3">
            <h2 class="panel-head">Source</h2>
            <div style="padding:1rem">
                <MonacoEditor @ref="_editor" @bind-Value="_form.SourceCode" Height="420px"
                              MarkersChanged="OnMarkersChanged" />
                <ScriptProblemsList Report="_markers" OnSelect="RevealProblemAsync" />
                <div class="form-text">SHA-256 hash is computed automatically on save.</div>
            </div>
        </section>

        @if (!string.IsNullOrWhiteSpace(_error)) { <div class="panel notice notice-alert mt-3">@_error</div> }

        <div class="mt-3 d-flex gap-2">
            <div class="btn-group" role="group">
                <button type="submit" class="btn btn-primary" disabled="@_busy">@(IsNew ? "Create" : "Save changes")</button>
                <a href="/scripts" class="btn btn-outline-secondary">Cancel</a>
            </div>
            @if (!IsNew) { <button type="button" class="btn btn-outline-danger ms-auto" @onclick="() => _confirmDeleteVisible = true" disabled="@_busy">Delete</button> }
        </div>
    </EditForm>

    @* R04 H1: the delete used to run on the first click. *@
    <RawConfirmDialog @bind-Visible="_confirmDeleteVisible" Title="Delete script"
                      Message="@($"Delete the script '{_existing?.Name ?? _form.Name}'? This cannot be undone.")"
                      OnConfirm="DeleteAsync" />
}
</PageErrorBoundary>

@code {
    [Parameter] public string? ScriptId { get; set; }
    private bool IsNew => string.IsNullOrEmpty(ScriptId);

    private FormModel _form = new();
    private Script? _existing;
    private bool _loaded;
    private bool _busy;
    private string? _error;
    private bool _confirmDeleteVisible;
    private MonacoEditor? _editor;
    private ScriptProblemReport _markers = ScriptProblemReport.Empty;

    private void OnMarkersChanged(ScriptProblemReport report) => _markers = report;

    private Task RevealProblemAsync(DiagnosticMarker m)
        => _editor is null ? Task.CompletedTask : _editor.RevealLineAsync(m.StartLineNumber, m.StartColumn);

    protected override async Task OnInitializedAsync()
    {
        if (!IsNew)
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            _existing = await db.Scripts.AsNoTracking().FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
            if (_existing is not null)
            {
                _form = new FormModel
                {
                    ScriptId = _existing.ScriptId,
                    Name = _existing.Name,
                    SourceCode = _existing.SourceCode,
                    RowVersion = _existing.RowVersion,
                };
            }
        }
        _loaded = true;
    }

    private async Task SubmitAsync(EditContext editContext)
    {
        _busy = true; _error = null;
        try
        {
            // The editor reports its text only at blur, so read the authoritative current value now. A read
            // failure (e.g. the script is too large to send) aborts the save rather than persisting stale source.
            if (_editor is not null)
            {
                var read = await _editor.GetValueAsync();
                if (!read.Ok) { _error = $"Not saved: {read.Error}"; return; }
                _form.SourceCode = read.Value!;
            }
            if (!editContext.Validate()) return;

            var sourceHash = HashSource(_form.SourceCode);
            await using var db = await DbFactory.CreateDbContextAsync();
            if (IsNew)
            {
                // ScriptId is system-generated (mirrors EquipmentId's "EQ-{12 hex}" convention);
                // Language is always CSharp.
                db.Scripts.Add(new Script
                {
                    ScriptId = $"SC-{Guid.NewGuid().ToString("N")[..12]}",
                    Name = _form.Name,
                    Language = "CSharp",
                    SourceCode = _form.SourceCode,
                    SourceHash = sourceHash,
                });
            }
            else
            {
                var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
                if (entity is null) { _error = "Row no longer exists."; return; }
                db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
                entity.Name = _form.Name;
                entity.SourceCode = _form.SourceCode;
                entity.SourceHash = sourceHash;
            }
            await db.SaveChangesAsync();
            Nav.NavigateTo("/scripts");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this script while you were editing."; }
        catch (Exception ex) { _error = ex.Message; }
        finally { _busy = false; }
    }

    private async Task DeleteAsync()
    {
        if (IsNew) return;
        _busy = true; _error = null;
        try
        {
            await using var db = await DbFactory.CreateDbContextAsync();
            var entity = await db.Scripts.FirstOrDefaultAsync(s => s.ScriptId == ScriptId);
            if (entity is null) { Nav.NavigateTo("/scripts"); return; }
            db.Entry(entity).Property(e => e.RowVersion).OriginalValue = _form.RowVersion;
            db.Scripts.Remove(entity);
            await db.SaveChangesAsync();
            Nav.NavigateTo("/scripts");
        }
        catch (DbUpdateConcurrencyException) { _error = "Another user changed this script while you were viewing it."; }
        catch (Exception ex) { _error = $"Delete failed: {ex.Message}. Likely because virtual tags or scripted alarms still reference this script — remove them first."; }
        finally { _busy = false; }
    }

    private static string HashSource(string source) =>
        Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(source)));

    private sealed class FormModel
    {
        // ScriptId is system-generated, display-only (not user-entered) — no validation.
        public string ScriptId { get; set; } = "";
        [Required] public string Name { get; set; } = "";
        [Required] public string SourceCode { get; set; } = "";
        public byte[] RowVersion { get; set; } = [];
    }
}
