package spindle

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"github.com/bluesky-social/indigo/atproto/syntax"
)

func AdminAllowMember(ctx context.Context, url, password, did string) error {
	if _, err := syntax.ParseDID(did); err != nil {
		return fmt.Errorf("invalid did %q: %w", did, err)
	}

	return postAdmin(ctx, password, url+"/admin/member/allow", adminReq{Did: did})
}

func AdminBlockMember(ctx context.Context, url, password, did string) error {
	if _, err := syntax.ParseDID(did); err != nil {
		return fmt.Errorf("invalid did %q: %w", did, err)
	}

	return postAdmin(ctx, password, url+"/admin/member/block", adminReq{Did: did})
}

func postAdmin(ctx context.Context, password, url string, body any) error {
	encoded, _ := json.Marshal(body)
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(encoded))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth("admin", password)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode/100 != 2 {
		msg, _ := io.ReadAll(resp.Body)
		return fmt.Errorf("spindle returned %s: %s", resp.Status, bytes.TrimSpace(msg))
	}
	return nil
}
