using System.IO.Compression;
using System.Reflection;

namespace NexusInstaller.Services;

internal static class PayloadExtractor
{
    public static void ExtractTo(string installRoot)
    {
        Directory.CreateDirectory(installRoot);

        var zipPath = ResolvePayloadZipPath();
        var tempZip = Path.Combine(Path.GetTempPath(), $"nexus-payload-{Guid.NewGuid():N}.zip");
        try
        {
            File.Copy(zipPath, tempZip, overwrite: true);
            ZipFile.ExtractToDirectory(tempZip, installRoot, overwriteFiles: true);
        }
        finally
        {
            if (File.Exists(tempZip))
            {
                File.Delete(tempZip);
            }
        }
    }

    private static string ResolvePayloadZipPath()
    {
        var assembly = Assembly.GetExecutingAssembly();
        var resourceName = assembly.GetManifestResourceNames()
            .FirstOrDefault(n => n.EndsWith("payload.zip", StringComparison.OrdinalIgnoreCase));

        if (resourceName is not null)
        {
            var tempZip = Path.Combine(Path.GetTempPath(), $"nexus-embedded-{Guid.NewGuid():N}.zip");
            using var stream = assembly.GetManifestResourceStream(resourceName)
                ?? throw new InvalidOperationException("Embedded payload.zip stream missing.");
            using var file = File.Create(tempZip);
            stream.CopyTo(file);
            return tempZip;
        }

        var sibling = Path.Combine(AppContext.BaseDirectory, "nexus-shell-poc.zip");
        if (File.Exists(sibling))
        {
            return sibling;
        }

        throw new FileNotFoundException(
            "POC package not found. Rebuild with build-installer.ps1 or place nexus-shell-poc.zip next to NexusSetup.exe.");
    }
}
