using System.Net;
using System.Net.Http.Json;
using CashLineERP.Contracts.Workflow;

namespace CashLineERP.Api.Tests;

public sealed class WorkflowAdministrationQaTests : IClassFixture<ApiTestFactory>
{
    private readonly HttpClient _client;

    public WorkflowAdministrationQaTests(ApiTestFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task Workflow_Administration_Endpoints_Return_Rules_And_Instance_Detail()
    {
        await _client.AuthenticateAsInternalAsync();

        var rulesResponse = await _client.GetAsync("/api/v1/workflow/rules?activeOnly=true");
        Assert.Equal(HttpStatusCode.OK, rulesResponse.StatusCode);
        var rules = await rulesResponse.Content.ReadFromJsonAsync<List<WorkflowRuleAdminResponse>>();
        Assert.NotNull(rules);
        Assert.Contains(rules!, rule => rule.ModuleCode == "PROCUREMENT" && rule.DocumentType == "PURCHASE_REQUISITION");

        var instancesResponse = await _client.GetAsync("/api/v1/workflow/instances?moduleCode=PROCUREMENT&documentType=PURCHASE_REQUISITION&statusCode=SUBMITTED");
        Assert.Equal(HttpStatusCode.OK, instancesResponse.StatusCode);
        var instances = await instancesResponse.Content.ReadFromJsonAsync<List<WorkflowInstanceSummaryResponse>>();
        Assert.NotNull(instances);
        var instance = Assert.Single(instances!);
        Assert.Equal("PR-000001", instance.DocumentNumber);

        var detailResponse = await _client.GetAsync($"/api/v1/workflow/instances/{instance.WorkflowInstanceId}");
        Assert.Equal(HttpStatusCode.OK, detailResponse.StatusCode);
        var detail = await detailResponse.Content.ReadFromJsonAsync<WorkflowInstanceResponse>();
        Assert.NotNull(detail);
        Assert.Equal(instance.WorkflowInstanceId, detail!.WorkflowInstanceId);
        Assert.NotEmpty(detail.Actions);
    }
}
