using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;

namespace CartWise.Web.Tests;

public class HouseholdAccessControlTests : IClassFixture<CartWiseWebApplicationFactory>
{
    private readonly CartWiseWebApplicationFactory _factory;

    public HouseholdAccessControlTests(CartWiseWebApplicationFactory factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task AnonymousUser_IsRedirectedToLoginWhenRequestingHousehold()
    {
        var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });

        var response = await client.GetAsync("/household");

        Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
        Assert.Contains("/Account/Login", response.Headers.Location?.ToString());
    }

    [Fact]
    public async Task EachUser_OnlySeesTheirOwnHousehold()
    {
        var clientA = _factory.CreateClient();
        var clientB = _factory.CreateClient();

        await WebTestHelpers.RegisterAsync(clientA, "alice2@example.com", "Alice");
        await WebTestHelpers.RegisterAsync(clientB, "bob2@example.com", "Bob");

        await WebTestHelpers.CreateHouseholdAsync(clientA, "Alice's Household");
        await WebTestHelpers.CreateHouseholdAsync(clientB, "Bob's Household");

        var householdPageA = await clientA.GetStringAsync("/household");
        var householdPageB = await clientB.GetStringAsync("/household");

        HtmlAssert.Contains("Alice's Household", householdPageA);
        HtmlAssert.DoesNotContain("Bob's Household", householdPageA);

        HtmlAssert.Contains("Bob's Household", householdPageB);
        HtmlAssert.DoesNotContain("Alice's Household", householdPageB);
    }
}
