package blobstore

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"github.com/bluesky-social/indigo/atproto/identity"
	"github.com/bluesky-social/indigo/atproto/syntax"
	"github.com/ipfs/go-cid"
)

type Pds struct {
	dir identity.Directory
}

func NewPdsBlobStore(dir identity.Directory) *Pds {
	return &Pds{dir}
}

var _ BlobStore = new(Pds)

func (s *Pds) GetBlobUrl(ctx context.Context, did syntax.DID, cid cid.Cid) (string, error) {
	id, err := s.dir.LookupDID(ctx, did)
	if err != nil {
		return "", err
	}

	url, _ := url.Parse(fmt.Sprintf("%s/xrpc/com.atproto.sync.getBlob", id.PDSEndpoint()))
	q := url.Query()
	q.Set("did", did.String())
	q.Set("cid", cid.String())
	url.RawQuery = q.Encode()

	return url.String(), nil
}

func (s *Pds) GetBlob(ctx context.Context, did syntax.DID, cid cid.Cid) (io.ReadCloser, error) {
	url, err := s.GetBlobUrl(ctx, did, cid)
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("unexpected status: %s", resp.Status)
	}

	return resp.Body, nil
}
