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

namespace Baya.Test.Api;

public class NurseProfilesApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    [Fact]
    public async Task Upsert_ThenMe_CreatesUnverifiedProfileWithZeroAggregates()
    {
        var client = factory.CreateClient();
        await ProfileTestClient.AuthenticateAsync(factory, client, "09121000001", "nurse");

        var upsert = await client.PostAsJsonAsync("/api/v1/nurse_profiles/upsert",
            new { bio = "20 years in geriatric care", yearsOfExperience = 20, educationLevel = "BSc", educationField = "Nursing", specializationsJson = "[\"elderly\"]" });
        Assert.Equal(HttpStatusCode.OK, upsert.StatusCode);

        var me = await client.GetAsync("/api/v1/nurse_profiles/me");
        Assert.Equal(HttpStatusCode.OK, me.StatusCode);
        var data = await AuthTestClient.ReadDataAsync(me);

        Assert.False(data.GetProperty("isVerified").GetBoolean());
        Assert.False(data.GetProperty("isAcceptingBookings").GetBoolean());
        Assert.Equal(0, data.GetProperty("totalReviews").GetInt32());
        Assert.Equal(20, data.GetProperty("yearsOfExperience").GetInt32());
    }

    [Fact]
    public async Task SetAcceptingBookings_TogglesWithoutVerifying()
    {
        var client = factory.CreateClient();
        await ProfileTestClient.AuthenticateAsync(factory, client, "09121000002", "nurse");
        await client.PostAsJsonAsync("/api/v1/nurse_profiles/upsert",
            new { bio = "b", yearsOfExperience = 3, educationLevel = "", educationField = "", specializationsJson = "[]" });

        var toggle = await client.PostAsJsonAsync("/api/v1/nurse_profiles/set_accepting_bookings", new { accepting = true });
        Assert.Equal(HttpStatusCode.OK, toggle.StatusCode);

        var me = await client.GetAsync("/api/v1/nurse_profiles/me");
        var data = await AuthTestClient.ReadDataAsync(me);
        Assert.True(data.GetProperty("isAcceptingBookings").GetBoolean());
        Assert.False(data.GetProperty("isVerified").GetBoolean());
    }

    [Fact]
    public async Task Me_Unauthenticated_Returns401()
    {
        var client = factory.CreateClient();
        var response = await client.GetAsync("/api/v1/nurse_profiles/me");
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    [Fact]
    public async Task Upsert_InvalidExperience_Returns400()
    {
        var client = factory.CreateClient();
        await ProfileTestClient.AuthenticateAsync(factory, client, "09121000003", "nurse");

        var response = await client.PostAsJsonAsync("/api/v1/nurse_profiles/upsert",
            new { bio = "b", yearsOfExperience = -5, educationLevel = "", educationField = "", specializationsJson = "[]" });

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}
