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

namespace Baya.Test.Api;

public class AdminInvoicesApiTests(BayaApiFactory factory) : IClassFixture<BayaApiFactory>
{
    [Fact]
    public async Task Issue_Unauthenticated_Returns401()
    {
        var client = factory.CreateClient();
        var response = await client.PostAsJsonAsync("/api/v1/admin_invoices", new { bookingId = 1 });
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    [Fact]
    public async Task Issue_computes_vat_on_commission_and_returns_sequential_number()
    {
        var admin = factory.CreateClient();
        await AdminTestClient.AuthenticateAsync(factory, admin, "09131901501");
        var bookingId = await AdminRefundsApiTests.SeedCapturedBookingAsync(factory, "09131901502");

        var issue = await admin.PostAsJsonAsync("/api/v1/admin_invoices", new { bookingId });
        Assert.Equal(HttpStatusCode.OK, issue.StatusCode);
        var data = await AuthTestClient.ReadDataAsync(issue);

        Assert.False(string.IsNullOrEmpty(data.GetProperty("invoiceNumber").GetString()));
        Assert.Equal("1500000", data.GetProperty("platformCommissionIrr").GetString());
        Assert.Equal("150000", data.GetProperty("vatIrr").GetString()); // 10% of the commission line
        Assert.Equal("pending", data.GetProperty("moadianStatus").GetString());

        // Re-issue is idempotent — same number, no second invoice.
        var reissue = await admin.PostAsJsonAsync("/api/v1/admin_invoices", new { bookingId });
        var reissued = await AuthTestClient.ReadDataAsync(reissue);
        Assert.Equal(data.GetProperty("invoiceNumber").GetString(), reissued.GetProperty("invoiceNumber").GetString());

        // The booking's invoice is readable via the customer/admin GET.
        var get = await admin.GetAsync($"/api/v1/invoices/{bookingId}");
        Assert.Equal(HttpStatusCode.OK, get.StatusCode);
    }
}
