using System.Net;
using System.Net.Http.Json;
using System.Security.Claims;
using System.Text.Json;
using WorkClub.Domain.Enums;
using WorkClub.Application.Clubs.DTOs;
using WorkClub.Tests.Integration.Infrastructure;
using Xunit;

namespace WorkClub.Tests.Integration.Clubs;

public class AdminClubEndpointsTests : IntegrationTestBase
{
    public AdminClubEndpointsTests(CustomWebApplicationFactory<Program> factory) : base(factory)
    {
    }

    [Fact]
    public async Task CreateClub_WithAdminRole_ReturnsCreated()
    {
        AuthenticateAsAdmin();

        var request = new CreateClubRequest("New Admin Club", SportType.Tennis, "Desc");
        var response = await Client.PostAsJsonAsync("/api/admin/clubs", request);

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

    [Fact]
    public async Task CreateClub_WithoutAdminRole_ReturnsForbidden()
    {
        AuthenticateAsNonAdmin();

        var request = new CreateClubRequest("New Club", SportType.Tennis, "Desc");
        var response = await Client.PostAsJsonAsync("/api/admin/clubs", request);

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

    private void AuthenticateAsAdmin()
    {
        Client.DefaultRequestHeaders.Remove("X-Test-Email");
        Client.DefaultRequestHeaders.Add("X-Test-Email", "admin@workclub.com");
        
        Client.DefaultRequestHeaders.Remove("X-Test-Realm-Access");
        Client.DefaultRequestHeaders.Add("X-Test-Realm-Access", "{\"roles\":[\"admin\"]}");
    }

    private void AuthenticateAsNonAdmin()
    {
        Client.DefaultRequestHeaders.Remove("X-Test-Email");
        Client.DefaultRequestHeaders.Add("X-Test-Email", "user@workclub.com");
        
        Client.DefaultRequestHeaders.Remove("X-Test-Realm-Access");
        Client.DefaultRequestHeaders.Add("X-Test-Realm-Access", "{\"roles\":[\"user\"]}");
    }
}
