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

namespace CartWise.Web.Tests;

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

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

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

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

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

    [Fact]
    public async Task AuthenticatedUser_CanReachScanPage()
    {
        var client = _factory.CreateClient();
        await WebTestHelpers.RegisterAsync(client, "scanuser1@example.com", "Scan User");

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

        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        HtmlAssert.Contains("Scan a barcode", body);
    }

    [Fact]
    public async Task BarcodeHtmlRoute_ReturnsNotFoundForUnknownBarcode()
    {
        var client = _factory.CreateClient();
        await WebTestHelpers.RegisterAsync(client, "scanuser2@example.com", "Scan User 2");

        var response = await client.GetAsync("/products/barcode/000000000000");

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

    [Fact]
    public async Task BarcodeJsonRoute_ReturnsFoundFalseForUnknownBarcode()
    {
        var client = _factory.CreateClient();
        await WebTestHelpers.RegisterAsync(client, "scanuser3@example.com", "Scan User 3");

        var response = await client.GetAsync("/api/products/barcode/000000000000");

        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        Assert.Contains("\"found\":false", body);
    }
}
