using System.Net;

namespace Baya.Test.Api;

public class GeoApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    // Seeded ids: Tehran province = 1, Tehran city = 101, Mashhad city = 105 (no districts).
    private const long TehranProvinceId = 1;
    private const long TehranCityId = 101;
    private const long MashhadCityId = 105;

    [Fact]
    public async Task Provinces_ReturnsSeeded31_TehranFirst()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync("/api/v1/geo/provinces");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var provinces = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray().ToList();
        Assert.Equal(31, provinces.Count);
        Assert.Equal("Tehran", provinces[0].GetProperty("nameEn").GetString());
    }

    [Fact]
    public async Task Cities_ForTehranProvince_IncludesTehran()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync($"/api/v1/geo/cities?province_id={TehranProvinceId}");
        var cities = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray().ToList();

        Assert.Contains(cities, c => c.GetProperty("id").GetInt64() == TehranCityId);
    }

    [Fact]
    public async Task Districts_ForTehran_Returns22()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync($"/api/v1/geo/districts?city_id={TehranCityId}");
        var districts = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray().ToList();

        Assert.Equal(22, districts.Count);
    }

    [Fact]
    public async Task Districts_ForMashhad_IsEmpty_WholeCityOnly()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync($"/api/v1/geo/districts?city_id={MashhadCityId}");
        var districts = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray().ToList();

        Assert.Empty(districts);
    }

    [Fact]
    public async Task Tree_ReturnsActiveHierarchy()
    {
        var client = factory.CreateClient();

        var response = await client.GetAsync("/api/v1/geo/tree");
        Assert.Equal(HttpStatusCode.OK, response.StatusCode);

        var provinces = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray().ToList();
        Assert.Equal(31, provinces.Count);
        var tehran = provinces.Single(p => p.GetProperty("id").GetInt64() == TehranProvinceId);
        Assert.NotEmpty(tehran.GetProperty("cities").EnumerateArray());
    }
}
