using System.Net;

namespace Baya.Test.Api;

/// <summary>
/// Refinement Phase 0 — proves the integration seam the browser depends on: the named CORS policy answers a
/// pre-flight from the client's origin (and only that origin), and the Development-only OTP helper is a hard
/// 404 in any non-Development environment (the factory boots as "Testing").
/// </summary>
public class CorsAndDevBringUpTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    private const string AllowedOrigin = "http://localhost:3000";
    private const string CorsOriginHeader = "Access-Control-Allow-Origin";

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

        var request = new HttpRequestMessage(HttpMethod.Options, "/api/v1/auth/request_otp");
        request.Headers.Add("Origin", AllowedOrigin);
        request.Headers.Add("Access-Control-Request-Method", "POST");
        request.Headers.Add("Access-Control-Request-Headers", "authorization,content-type");

        var response = await client.SendAsync(request);

        Assert.True(response.Headers.TryGetValues(CorsOriginHeader, out var origins),
            "the pre-flight for an allowed origin must carry Access-Control-Allow-Origin");
        Assert.Equal(AllowedOrigin, Assert.Single(origins));
    }

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

        var request = new HttpRequestMessage(HttpMethod.Options, "/api/v1/auth/request_otp");
        request.Headers.Add("Origin", "https://evil.example");
        request.Headers.Add("Access-Control-Request-Method", "POST");

        var response = await client.SendAsync(request);

        Assert.False(response.Headers.Contains(CorsOriginHeader),
            "a foreign origin must never be echoed back as allowed");
    }

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

        var response = await client.GetAsync("/api/v1/dev/last_otp/09120000001");

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