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

namespace Baya.Test.Api;

public class AdminGeoApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    private const long TehranProvinceId = 1;

    [Fact]
    public async Task CreateCity_ThenDeactivate_HidesWithoutDeleting()
    {
        var client = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, client, "09129000001");

        var create = await client.PostAsJsonAsync("/api/v1/admin_geo/create_city",
            new { provinceId = TehranProvinceId, nameFa = "شهر آزمایشی", nameEn = "Test City", sortOrder = 99 });
        Assert.Equal(HttpStatusCode.OK, create.StatusCode);
        var cityId = (await AuthTestClient.ReadDataAsync(create)).GetProperty("id").GetInt64();

        // Public list includes the new active city.
        Assert.True(await CityVisible(client, cityId));

        // Deactivate → it disappears from the public dropdown, but is not deleted.
        var deactivate = await client.PostAsJsonAsync($"/api/v1/admin_geo/set_city_active/{cityId}", new { isActive = false });
        Assert.Equal(HttpStatusCode.OK, deactivate.StatusCode);
        Assert.False(await CityVisible(client, cityId));

        // Reactivate → it returns.
        var reactivate = await client.PostAsJsonAsync($"/api/v1/admin_geo/set_city_active/{cityId}", new { isActive = true });
        Assert.Equal(HttpStatusCode.OK, reactivate.StatusCode);
        Assert.True(await CityVisible(client, cityId));
    }

    [Fact]
    public async Task CreateProvince_Unauthenticated_Returns401()
    {
        var client = factory.CreateClient();
        var response = await client.PostAsJsonAsync("/api/v1/admin_geo/create_province",
            new { nameFa = "x", nameEn = "x", sortOrder = 1 });
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    [Fact]
    public async Task CreateProvince_MissingName_Returns400()
    {
        var client = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, client, "09129000002");

        var response = await client.PostAsJsonAsync("/api/v1/admin_geo/create_province",
            new { nameFa = "", nameEn = "", sortOrder = 1 });
        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }

    private static async Task<bool> CityVisible(HttpClient client, long cityId)
    {
        var response = await client.GetAsync($"/api/v1/geo/cities?province_id={TehranProvinceId}");
        var cities = (await AuthTestClient.ReadDataAsync(response)).EnumerateArray();
        return cities.Any(c => c.GetProperty("id").GetInt64() == cityId);
    }
}
