using System.Text.Json;
using Sdt.Config;
using Xunit;

namespace DevTool.Tests;

public sealed class LegacyModeTests
{
    [Fact]
    public void ConfigLoader_StrictMode_TargetsOnly_FailsAndWritesPreview()
    {
        var root = CreateTempDir();
        WriteLegacyTargetsOnlyConfig(root);
        Environment.SetEnvironmentVariable("SDT_LEGACY_MODE", null);

        var ex = Assert.Throws<InvalidOperationException>(() => ConfigLoader.FindAndLoad(root));
        Assert.Contains("Strict mode requires workflows", ex.Message, StringComparison.OrdinalIgnoreCase);
        Assert.True(File.Exists(Path.Combine(root, "devtool.generated.workflows.json")));
    }

    [Fact]
    public void ConfigLoader_CompatMode_TargetsOnly_Loads()
    {
        var root = CreateTempDir();
        WriteLegacyTargetsOnlyConfig(root);
        Environment.SetEnvironmentVariable("SDT_LEGACY_MODE", "compat");
        try
        {
            var loaded = ConfigLoader.FindAndLoad(root);
            Assert.NotNull(loaded);
            Assert.Contains(loaded!.Warnings, w => w.Contains("legacy 'targets'", StringComparison.OrdinalIgnoreCase));
        }
        finally
        {
            Environment.SetEnvironmentVariable("SDT_LEGACY_MODE", null);
        }
    }

    [Fact]
    public void ApplyLegacyTargetMigration_RewritesConfigAndCreatesBackup()
    {
        var root = CreateTempDir();
        WriteLegacyTargetsOnlyConfig(root);
        var path = Path.Combine(root, "devtool.json");

        var result = ConfigLoader.ApplyLegacyTargetMigration(path, createBackup: true);

        Assert.True(result.Success);
        Assert.True(File.Exists(path));
        Assert.False(string.IsNullOrWhiteSpace(result.BackupPath));
        Assert.True(File.Exists(result.BackupPath!));

        var loaded = ConfigLoader.FindAndLoad(root);
        Assert.NotNull(loaded);
        Assert.NotEmpty(loaded!.Config.Workflows);
        Assert.Empty(loaded.Config.Targets);
    }

    private static void WriteLegacyTargetsOnlyConfig(string root)
    {
        var cfg = new DevToolConfig
        {
            Name = "legacy",
            Version = "0.1.0",
            Targets =
            [
                new BuildTarget
                {
                    Id = "build",
                    Label = "Build",
                    Command = "dotnet",
                    Args = ["build"]
                }
            ],
            Workflows = []
        };

        var json = JsonSerializer.Serialize(cfg, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, WriteIndented = true });
        File.WriteAllText(Path.Combine(root, "devtool.json"), json);
    }

    private static string CreateTempDir()
    {
        var path = Path.Combine(Path.GetTempPath(), "sdt-legacy-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(path);
        return path;
    }
}
