import Foundation

// Home timeline pagination. Mastodon's API uses Link-header pagination:
// `Link: <…?max_id=X>; rel="next"`. This extension parses the header
// and surfaces the next-page cursor alongside the decoded statuses so
// the view can append on scroll-bottom.

struct WatchHomeFeedPage {
    let statuses: [WatchStatus]
    let nextMaxId: String?
}

extension WatchAPIClient {
    func fetchHomeFeed(maxId: String? = nil, limit: Int = 20) async throws -> WatchHomeFeedPage {
        guard
            let url = Endpoints.homeTimeline(
                instance,
                accountType: accountType,
                maxId: maxId,
                limit: limit
            )
        else {
            throw WatchAPIError.invalidURL
        }
        let (statuses, response) = try await request(url, decode: [WatchStatus].self)
        let next = parseNextMaxId(linkHeader: response.value(forHTTPHeaderField: "Link"))
        return WatchHomeFeedPage(statuses: statuses, nextMaxId: next)
    }

    private func parseNextMaxId(linkHeader: String?) -> String? {
        guard let header = linkHeader else { return nil }
        // `Link` value example:
        //   <https://example/api/v1/timelines/home?max_id=ABC>; rel="next",
        //   <https://example/api/v1/timelines/home?since_id=DEF>; rel="prev"
        for chunk in header.split(separator: ",") {
            let trimmed = chunk.trimmingCharacters(in: .whitespaces)
            guard trimmed.contains("rel=\"next\"") else { continue }
            if let lt = trimmed.firstIndex(of: "<"),
                let gt = trimmed.firstIndex(of: ">"),
                lt < gt
            {
                let urlStr = String(trimmed[trimmed.index(after: lt)..<gt])
                if let comps = URLComponents(string: urlStr),
                    let item = comps.queryItems?.first(where: { $0.name == "max_id" })
                {
                    return item.value
                }
            }
        }
        return nil
    }
}
