import { Listing } from '@devvit/protos/types/devvit/plugin/redditapi/common/common_msg.js';
import { ListingResponse, } from '@devvit/protos/types/devvit/plugin/redditapi/listings/listings_msg.js';
import { Buffer } from '../../lib/Buffer.js';
import { findAndThrowRedditAPIError } from './errors.js';
import { RedditAPI } from './RedditAPI.js';
import { deepSnakeToCamel } from './snakeToCamel.js';
export class Listings extends RedditAPI {
    async Best(request, metadata) {
        const response = await this._fetch('Best', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
    async ById(request, metadata) {
        const response = await this._fetch('ById', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
    async Comments(request, metadata) {
        const response = await this._fetch('Comments', request, metadata);
        const body = JSON.parse(new TextDecoder().decode(Buffer.from(response.body)));
        findAndThrowRedditAPIError(response.status, body);
        if (Array.isArray(body) && body[1] != null) {
            body[1] = fixCommentReplies(body[1]);
        }
        return ListingResponse.fromJSON({
            listings: deepSnakeToCamel(body),
        });
    }
    async Duplicates(request, metadata) {
        const response = await this._fetch('Duplicates', request, metadata);
        return ListingResponse.fromJSON({
            listings: this._decodeAndValidateResponseJSON(response),
        });
    }
    async Hot(request, metadata) {
        const response = await this._fetch('Hot', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
    async New(request, metadata) {
        const response = await this._fetch('New', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
    async Rising(request, metadata) {
        const response = await this._fetch('Rising', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
    async Sort(request, metadata) {
        const response = await this._fetch('Sort', request, metadata);
        return Listing.fromJSON(this._decodeAndValidateResponseJSON(response));
    }
}
// Copy the value of `replies` to `reply_list`
// This is need so that `RedditObject.fromJSON` will properly parse the Listing.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function fixCommentReplies(listing) {
    if (!listing.data?.children) {
        return listing;
    }
    const newListing = Object.assign({}, listing);
    for (const wrappedComment of newListing.data.children) {
        const comment = wrappedComment.data;
        if (comment?.replies) {
            comment.reply_list = fixCommentReplies(comment.replies);
            delete comment.replies;
        }
    }
    return newListing;
}
