using Kompas.Mcp.Core.Documents;
using Kompas.Mcp.Core.Drawings;

namespace Kompas.Mcp.Tests.Integration;

/// <summary>Интеграция: технические требования чертежа (API7 IDrawingDocument.TechnicalDemand).</summary>
[Trait("Category", "Integration")]
[Collection(KompasCollection.Name)]
public sealed class DrawingTechReqTests : IntegrationTestBase
{
    private readonly DocumentService _docs;
    private readonly DrawingService _drawing;

    public DrawingTechReqTests(KompasFixture fx) : base(fx)
    {
        _docs = new DocumentService(fx.Session, fx.Dispatcher);
        _drawing = new DrawingService(fx.Session, fx.Dispatcher);
    }

    [Fact]
    public async Task Requirements_are_set_and_read_back()
    {
        await _docs.CreateAsync(KompasDocumentType.Drawing);
        try
        {
            var text = "1. Общие допуски по ГОСТ 30893.1.\n2. Острые кромки притупить.";
            var lines = await _drawing.SetTechnicalRequirementsAsync(text);
            Assert.Equal(2, lines);

            var readBack = await _drawing.ReadTechnicalRequirementsAsync();
            Assert.Contains("Общие допуски", readBack);
            Assert.Contains("Острые кромки", readBack);
        }
        finally { await _docs.CloseAsync(save: false); }
    }

    [Fact]
    public async Task Overwrite_replaces_previous()
    {
        await _docs.CreateAsync(KompasDocumentType.Drawing);
        try
        {
            await _drawing.SetTechnicalRequirementsAsync("1. Первая редакция.");
            await _drawing.SetTechnicalRequirementsAsync("1. Вторая редакция.\n2. Ещё пункт.");
            var readBack = await _drawing.ReadTechnicalRequirementsAsync();

            Assert.Contains("Вторая редакция", readBack);
            Assert.DoesNotContain("Первая редакция", readBack);
        }
        finally { await _docs.CloseAsync(save: false); }
    }

    [Fact]
    public async Task Empty_text_throws()
    {
        await _docs.CreateAsync(KompasDocumentType.Drawing);
        try
        {
            await Assert.ThrowsAsync<ArgumentException>(() =>
                _drawing.SetTechnicalRequirementsAsync("   "));
        }
        finally { await _docs.CloseAsync(save: false); }
    }

    [Fact]
    public async Task Active_document_not_drawing_throws()
    {
        await _docs.CreateAsync(KompasDocumentType.Part); // деталь, не чертёж
        try
        {
            await Assert.ThrowsAsync<InvalidOperationException>(() =>
                _drawing.SetTechnicalRequirementsAsync("1. Требование."));
        }
        finally { await _docs.CloseAsync(save: false); }
    }
}
