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

namespace Baya.Test.Api;

public class CustomerProfilesApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    [Fact]
    public async Task Upsert_ThenMe_RoundTripsThroughTheEncryptedColumn()
    {
        var client = factory.CreateClient();
        await ProfileTestClient.AuthenticateAsync(factory, client, "09122000001", "customer");

        var upsert = await client.PostAsJsonAsync("/api/v1/customer_profiles/upsert",
            new { defaultEmergencyContactName = "Ali", defaultEmergencyContactPhone = "09120000099" });
        Assert.Equal(HttpStatusCode.OK, upsert.StatusCode);

        // The value survives the encrypt-on-write / decrypt-on-read converter round-trip.
        var me = await client.GetAsync("/api/v1/customer_profiles/me");
        var data = await AuthTestClient.ReadDataAsync(me);
        Assert.Equal("Ali", data.GetProperty("defaultEmergencyContactName").GetString());
        Assert.Equal("09120000099", data.GetProperty("defaultEmergencyContactPhone").GetString());
    }

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

    [Fact]
    public async Task Upsert_InvalidEmergencyPhone_Returns400()
    {
        var client = factory.CreateClient();
        await ProfileTestClient.AuthenticateAsync(factory, client, "09122000002", "customer");

        var response = await client.PostAsJsonAsync("/api/v1/customer_profiles/upsert",
            new { defaultEmergencyContactName = "Ali", defaultEmergencyContactPhone = "not-a-phone" });

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