using Microsoft.AspNetCore.WebUtilities;
using RpgRoller.Contracts;

namespace RpgRoller.Components;

public sealed class WorkspaceQueryService(RpgRollerApiClient apiClient)
{
    public Task<MeResponse> GetMeAsync()
    {
        return apiClient.RequestAsync<MeResponse>("GET", "/api/me");
    }

    public async Task<IReadOnlyList<RulesetDefinition>> GetRulesetsAsync()
    {
        return await apiClient.RequestAsync<RulesetDefinition[]>("GET", "/api/rulesets");
    }

    public async Task<IReadOnlyList<CampaignSummary>> GetCampaignsAsync()
    {
        return await apiClient.RequestAsync<CampaignSummary[]>("GET", "/api/campaigns");
    }

    public async Task<IReadOnlyList<CampaignOption>> GetCharacterCampaignOptionsAsync()
    {
        return await apiClient.RequestAsync<CampaignOption[]>("GET", "/api/campaigns/options");
    }

    public Task<CampaignRoster> GetCampaignAsync(Guid campaignId)
    {
        return apiClient.RequestAsync<CampaignRoster>("GET", $"/api/campaigns/{campaignId:D}");
    }

    public async Task<IReadOnlyList<string>> GetUsernamesAsync()
    {
        return await apiClient.RequestAsync<string[]>("GET", "/api/users/usernames");
    }

    public Task<CharacterSheet> GetCharacterSheetAsync(Guid characterId)
    {
        return apiClient.RequestAsync<CharacterSheet>("GET", $"/api/characters/{characterId:D}/sheet");
    }

    public async Task<IReadOnlyList<CampaignLogEntry>> GetCampaignLogAsync(Guid campaignId)
    {
        return await apiClient.RequestAsync<CampaignLogEntry[]>("GET", $"/api/campaigns/{campaignId:D}/log");
    }

    public Task<CampaignLogPage> GetCampaignLogPageAsync(Guid campaignId, Guid? afterRollId = null, int? limit = null)
    {
        var query = new Dictionary<string, string?>();
        if (afterRollId.HasValue)
            query["afterRollId"] = afterRollId.Value.ToString("D");

        if (limit.HasValue)
            query["limit"] = limit.Value.ToString();

        var path = QueryHelpers.AddQueryString($"/api/campaigns/{campaignId:D}/log/page", query);
        return apiClient.RequestAsync<CampaignLogPage>("GET", path);
    }

    public Task<CampaignRollDetail> GetRollDetailAsync(Guid rollId)
    {
        return apiClient.RequestAsync<CampaignRollDetail>("GET", $"/api/rolls/{rollId:D}");
    }

    public async Task<IReadOnlyList<AdminUserSummary>> GetAdminUsersAsync()
    {
        return await apiClient.RequestAsync<AdminUserSummary[]>("GET", "/api/admin/users");
    }
}