using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using FluentAssertions;
using foodmarket.IntegrationTests.Support;
using Xunit;

namespace foodmarket.IntegrationTests;

[Collection(ApiCollection.Name)]
public class SignupFlowTests
{
    private readonly ApiFactory _factory;
    public SignupFlowTests(ApiFactory factory) => _factory = factory;

    [Fact]
    public async Task Signup_then_login_yields_token_with_org()
    {
        var actor = new ApiActor(_factory.CreateClient());
        var email = $"signup-{Guid.NewGuid():N}@example.kz";
        const string password = "Passw0rd!";

        var signup = await actor.SignupAsync(email, password, "Signup Org");
        signup.StatusCode.Should().Be(HttpStatusCode.OK);

        var token = await actor.TokenAsync(email, password);
        token.Should().NotBeNullOrEmpty();
        actor.UseToken(token);

        var me = await actor.GetJsonAsync("/api/me");
        me.GetProperty("email").GetString().Should().Be(email);
        me.GetProperty("orgId").GetString().Should().NotBeNullOrEmpty();
        me.GetProperty("hasLiveOrg").GetBoolean().Should().BeTrue();
    }

    [Fact]
    public async Task Duplicate_signup_is_rejected()
    {
        var actor = new ApiActor(_factory.CreateClient());
        var email = $"dup-{Guid.NewGuid():N}@example.kz";

        (await actor.SignupAsync(email, "Passw0rd!", "Dup Org 1")).StatusCode.Should().Be(HttpStatusCode.OK);
        var second = await actor.SignupAsync(email, "Passw0rd!", "Dup Org 2");
        second.StatusCode.Should().Be(HttpStatusCode.BadRequest);
    }

    [Fact]
    public async Task Weak_password_is_rejected()
    {
        var actor = new ApiActor(_factory.CreateClient());
        var resp = await actor.SignupAsync($"weak-{Guid.NewGuid():N}@example.kz", "short", "Weak Org");
        resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
    }
}
