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

namespace Baya.Test.Api;

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

    [Fact]
    public async Task List_AsAdmin_ReturnsSeededTiers()
    {
        var admin = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, admin, "09131900401");

        var response = await admin.GetAsync("/api/v1/admin_cancellation_policies/list");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        var data = await AuthTestClient.ReadDataAsync(response);
        // The four baseline tiers are seeded via HasData.
        Assert.True(data.GetArrayLength() >= 4);
    }

    [Fact]
    public async Task Upsert_InvalidPercentage_Returns400()
    {
        var admin = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, admin, "09131900402");

        var response = await admin.PostAsJsonAsync("/api/v1/admin_cancellation_policies/upsert", new
        {
            code = "custom_tier",
            appliesTo = "customer",
            refundPercentage = 150,
            feeAmountIrr = 0,
            isActive = true
        });

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

    [Fact]
    public async Task Upsert_AsAdmin_CreatesTier()
    {
        var admin = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, admin, "09131900403");

        var response = await admin.PostAsJsonAsync("/api/v1/admin_cancellation_policies/upsert", new
        {
            code = "late_customer",
            appliesTo = "customer",
            hoursBeforeStartMin = 0,
            hoursBeforeStartMax = 6,
            refundPercentage = 25,
            feeAmountIrr = 0,
            isActive = true
        });

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        var data = await AuthTestClient.ReadDataAsync(response);
        Assert.Equal("late_customer", data.GetProperty("code").GetString());
    }
}
