package controller

import (
	"arimelody-web/model"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"strings"
)

const BSKY_API_BASE = "https://public.api.bsky.app"

func FetchThreadViewPost(actorID string, postID string) (*model.ThreadViewPost, error) {
	uri := fmt.Sprintf("at://%s/app.bsky.feed.post/%s", actorID, postID)

    req, err := http.NewRequest(
        http.MethodGet,
        strings.Join([]string{BSKY_API_BASE, "xrpc", "app.bsky.feed.getPostThread"}, "/"),
        nil,
    )
    if err != nil { panic(err) }

    req.URL.RawQuery = url.Values{
        "uri": { uri },
    }.Encode()
    req.Header.Set("User-Agent", "ari melody [https://arimelody.me]")
    req.Header.Set("Accept", "application/json")

    client := &http.Client{}

    res, err := client.Do(req)
    if err != nil {
        return nil, errors.New(fmt.Sprintf("Failed to call Bluesky API: %v", err))
    }

    type Data struct {
        Thread model.ThreadViewPost `json:"thread"`
    }
    data := Data{}
    err = json.NewDecoder(res.Body).Decode(&data)
    if err != nil {
        return nil, errors.New(fmt.Sprintf("Invalid response from server: %v", err))
    }

    return &data.Thread, nil
}
