import Foundation

// Mirrors of the Pixelfed/Mastodon endpoints the watch needs. The phone
// side hits these via src/lib/api.ts and src/lib/tapestry/*; the watch
// hits the same URLs with its own URLSession-backed client.
//
// `_pe=1` is a Pixelfed-specific extended-response flag. Gated on
// `accountType == "pixelfed"` at every URL builder so a Mastodon
// account never has it appended, mirroring the phone-side ApiContext
// invariant (no `_pe=1` outside the per-account capability boundary).

enum Endpoints {
    static func base(_ instance: String) -> URL? {
        var c = URLComponents()
        c.scheme = "https"
        c.host = instance
        return c.url
    }

    static func tapestryBucket(_ instance: String, minute: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/tapestry/bucket/\(minute)")
    }

    static func tapestryPage(_ instance: String, page: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/tapestry/page/\(page)")
    }

    static func tapestrySince(_ instance: String, bucket: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/tapestry/since/\(bucket)")
    }

    static func tapestryPost(_ instance: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/tapestry")
    }

    static func homeTimeline(
        _ instance: String,
        accountType: String,
        maxId: String? = nil,
        limit: Int = 20
    ) -> URL? {
        var c = URLComponents(string: "https://\(instance)/api/v1/timelines/home")
        var items: [URLQueryItem] = [
            URLQueryItem(name: "limit", value: String(limit)),
        ]
        if accountType == "pixelfed" {
            items.append(URLQueryItem(name: "_pe", value: "1"))
        }
        if let maxId, !maxId.isEmpty {
            items.append(URLQueryItem(name: "max_id", value: maxId))
        }
        c?.queryItems = items
        return c?.url
    }

    static func favourite(_ instance: String, statusId: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/statuses/\(statusId)/favourite")
    }

    static func unfavourite(_ instance: String, statusId: String) -> URL? {
        URL(string: "https://\(instance)/api/v1/statuses/\(statusId)/unfavourite")
    }

    static func nodeinfo(_ instance: String) -> URL? {
        URL(string: "https://\(instance)/api/nodeinfo/2.0.json")
    }
}
