using System.Net;
using System.Net.Http.Json;

namespace Baya.Test.Api;

public class NursePayoutsApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    [Fact]
    public async Task History_Unauthenticated_Returns401()
    {
        var client = factory.CreateClient();
        var response = await client.GetAsync("/api/v1/nurse_payouts/history");
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    [Fact]
    public async Task History_AsNurse_ReturnsOwnPaidPayout_WithMaskedIban()
    {
        const string nursePhone = "09131903401";

        // Pay the nurse through the real admin flow, then read the nurse's own history.
        var admin = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, admin, "09131903402");
        await AdminPayoutsApiTests.SeedEligibleNurseBookingAsync(factory, nursePhone);

        var today = DateOnly.FromDateTime(DateTime.UtcNow).ToString("yyyy-MM-dd");
        var generate = await admin.PostAsJsonAsync("/api/v1/admin_payouts/batches",
            new { periodStart = "2020-01-01", periodEnd = today });
        Assert.Equal(HttpStatusCode.OK, generate.StatusCode);
        var batchId = (await AuthTestClient.ReadDataAsync(generate)).GetProperty("batch").GetProperty("id").GetInt64();
        var process = await admin.PostAsJsonAsync($"/api/v1/admin_payouts/batches/{batchId}/process", new { });
        Assert.Equal(HttpStatusCode.OK, process.StatusCode);

        var nurse = factory.CreateClient();
        var tokens = await AuthTestClient.LoginAsync(factory, nurse, nursePhone);
        AuthTestClient.UseBearer(nurse, tokens.GetProperty("accessToken").GetString()!);

        var response = await nurse.GetAsync("/api/v1/nurse_payouts/history?page=1&pageSize=20");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var data = await AuthTestClient.ReadDataAsync(response);
        Assert.True(data.GetProperty("total").GetInt32() >= 1);
        var item = data.GetProperty("items")[0];
        Assert.Equal("paid", item.GetProperty("status").GetString());
        Assert.Equal("8500000", item.GetProperty("netAmountIrr").GetString());
        Assert.Contains("•", item.GetProperty("maskedIban").GetString()!);
    }
}
