using System.Text.Json;
using System.Text.Json.Serialization;
using NexusInstaller.Models;

namespace NexusInstaller.Services;

internal static class NexusIdentitySeedService
{
    private static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = true,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
    };

    public static string Seed(
        OrganizationOption organization,
        string userEmail,
        string deviceFriendlyName,
        string roleName,
        string shellVersion,
        string agentVersion)
    {
        var identityDir = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "identity");

        Directory.CreateDirectory(identityDir);

        var now = DateTimeOffset.UtcNow;
        var deviceId = GenerateDeviceId();
        var userDisplay = userEmail.Contains('@')
            ? userEmail.Split('@')[0]
            : userEmail;

        var org = new
        {
            Id = organization.Id,
            Name = organization.Name,
            CreatedAtUtc = now,
        };

        var user = new
        {
            Id = $"USR-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}",
            DisplayName = userDisplay,
            OrganizationId = organization.Id,
            OrganizationName = organization.Name,
            Role = string.IsNullOrWhiteSpace(roleName) ? "User" : roleName.Trim(),
            CreatedAtUtc = now,
        };

        var device = new
        {
            DeviceId = deviceId,
            ComputerName = Environment.MachineName,
            FriendlyName = deviceFriendlyName.Trim(),
            Owner = userDisplay,
            Organization = organization.Name,
            AgentVersion = agentVersion,
            ShellVersion = shellVersion,
            EnrollmentDate = now,
            LastSeen = now,
            Status = "enrolled",
        };

        var trust = new
        {
            DeviceId = deviceId,
            Status = "pending",
            EvaluatedAtUtc = now,
            Reason = "Installer enrollment — afventer godkendelse",
        };

        Write(Path.Combine(identityDir, "organization.json"), org);
        Write(Path.Combine(identityDir, "user.json"), user);
        Write(Path.Combine(identityDir, "device.json"), device);
        Write(Path.Combine(identityDir, "trust.json"), trust);

        SeedPlatformLock();

        return deviceId;
    }

    private static void SeedPlatformLock()
    {
        var path = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "platform-lock.json");

        var state = new
        {
            Mode = 1, // Unlocked — installer does not enable lockdown
            LockedAtUtc = (DateTimeOffset?)null,
            Note = "POC — permanent lockdown requires explicit approval",
        };

        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        Write(path, state);
    }

    private static void Write(string path, object payload) =>
        File.WriteAllText(path, JsonSerializer.Serialize(payload, JsonOptions));

    private static string GenerateDeviceId() =>
        $"NEXUS-{Guid.NewGuid().ToString("N")[..8].ToUpperInvariant()}";
}
