package backup

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

// Archive is één archief zoals de backup server het meldt.
type Archive struct {
	Name      string    `json:"name"`
	CreatedAt time.Time `json:"created_at"`
	Size      int64     `json:"size"`
}

// RemoteStatus is wat de backup server over zichzelf zegt.
type RemoteStatus struct {
	Version     string    `json:"version"`
	ServerID    string    `json:"server_id"`
	LastSync    time.Time `json:"last_sync"`
	SyncError   string    `json:"sync_error,omitempty"`
	Syncs       int       `json:"syncs"`
	Notifies    int       `json:"notifies"`
	MirrorBytes int64     `json:"mirror_bytes"`
	LastStats   struct {
		Files      int   `json:"files"`
		Downloaded int   `json:"downloaded"`
		Bytes      int64 `json:"bytes"`
		Deleted    int   `json:"deleted"`
	} `json:"last_stats"`
	Archives     int       `json:"archives"`
	LastArchive  time.Time `json:"last_archive"`
	ArchiveError string    `json:"archive_error,omitempty"`
	Rollback     struct {
		State   string    `json:"state"`
		Archive string    `json:"archive,omitempty"`
		Error   string    `json:"error,omitempty"`
		At      time.Time `json:"at,omitempty"`
	} `json:"rollback"`
	Interval      string `json:"archive_interval"`
	RetentionDays int    `json:"retention_days"`
	RateLimitKiB  int64  `json:"rate_limit_kib"`
}

// Client praat ondertekend met de backup servers.
type Client struct {
	Manager *Manager
	HTTP    *http.Client
	Now     func() time.Time
}

// RemoteError is een foutantwoord van de backup server.
type RemoteError struct {
	Status int
	Msg    string
}

func (e *RemoteError) Error() string { return "backup server: " + e.Msg }

// Call stuurt een ondertekend verzoek naar backup server conn en geeft het
// ruwe antwoord terug. in is nil of wordt JSON.
func (c *Client) Call(ctx context.Context, conn Conn, method, p string, in any) (int, []byte, error) {
	if !conn.Connected() {
		return 0, nil, fmt.Errorf("backup server %s is niet gekoppeld", conn.Name)
	}
	inst, err := c.Manager.InstanceID()
	if err != nil {
		return 0, nil, err
	}
	var body []byte
	if in != nil {
		if body, err = json.Marshal(in); err != nil {
			return 0, nil, err
		}
	}
	req, err := http.NewRequestWithContext(ctx, method, conn.ServerURL+p, bytes.NewReader(body))
	if err != nil {
		return 0, nil, err
	}
	if in != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	now := time.Now
	if c.Now != nil {
		now = c.Now
	}
	Sign(req, conn.SignSecret, inst, body, now())
	SetOwnHeaders(req.Header)
	hc := c.HTTP
	if hc == nil {
		hc = &http.Client{Timeout: 15 * time.Second}
	}
	resp, err := hc.Do(req)
	if err != nil {
		return 0, nil, err
	}
	defer resp.Body.Close()
	// Alleen een antwoord met protocolkop zegt iets over de backup server
	// (een proxy-fout heeft er geen).
	if p, ok := PeerFromHeader(resp.Header); ok {
		c.Manager.SetPeer(conn.ID, p)
	}
	raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
	return resp.StatusCode, raw, nil
}

func (c *Client) do(ctx context.Context, conn Conn, method, p string, in, out any) error {
	code, raw, err := c.Call(ctx, conn, method, p, in)
	if err != nil {
		return err
	}
	if code >= 300 {
		var e struct {
			Error string `json:"error"`
		}
		_ = json.Unmarshal(raw, &e)
		if e.Error == "" {
			e.Error = http.StatusText(code)
		}
		return &RemoteError{Status: code, Msg: e.Error}
	}
	if out != nil {
		return json.Unmarshal(raw, out)
	}
	return nil
}

// Archives vraagt de lijst met archieven op, nieuwste eerst.
func (c *Client) Archives(ctx context.Context, conn Conn) ([]Archive, error) {
	var out struct {
		Archives []Archive `json:"archives"`
	}
	err := c.do(ctx, conn, http.MethodGet, "/api/v1/archives", nil, &out)
	return out.Archives, err
}

// Status vraagt de toestand van de backup server op.
func (c *Client) Status(ctx context.Context, conn Conn) (RemoteStatus, error) {
	var out RemoteStatus
	err := c.do(ctx, conn, http.MethodGet, "/api/v1/status", nil, &out)
	return out, err
}

// RemoteField is één instelling van de backup server.
type RemoteField struct {
	Key     string `json:"key"`
	Label   string `json:"label"`
	Help    string `json:"help"`
	Kind    string `json:"kind"`
	Restart bool   `json:"restart"`
	Value   string `json:"value"`
}

// RemoteConfig is GET /api/v1/admin/config van de backup server.
type RemoteConfig struct {
	Fields  []RemoteField `json:"fields"`
	DataDir string        `json:"data_dir"`
	Restart bool          `json:"restart_pending"`
}

// Config vraagt de instellingen van de backup server op.
func (c *Client) Config(ctx context.Context, conn Conn) (RemoteConfig, error) {
	var out RemoteConfig
	err := c.do(ctx, conn, http.MethodGet, "/api/v1/admin/config", nil, &out)
	return out, err
}

// RemoteAction is één beheeractie die de backup server aanbiedt.
type RemoteAction struct {
	Name   string   `json:"name"`
	Method string   `json:"method"`
	Path   string   `json:"path"`
	Title  string   `json:"title"`
	Signed bool     `json:"bluegit"`
	Params []string `json:"params"`
	Fields []string `json:"fields"`
}

// Actions vraagt op wat de backup server aanbiedt.
func (c *Client) Actions(ctx context.Context, conn Conn) ([]RemoteAction, error) {
	var out struct {
		Actions []RemoteAction `json:"actions"`
	}
	err := c.do(ctx, conn, http.MethodGet, "/api/v1/admin/actions", nil, &out)
	return out.Actions, err
}

// Rollback vraagt de backup server om archive terug te zetten. De server
// antwoordt meteen; het terugsturen naar BlueGit gebeurt daarna.
func (c *Client) Rollback(ctx context.Context, conn Conn, archive string) error {
	return c.do(ctx, conn, http.MethodPost, "/api/v1/rollback", map[string]string{"archive": archive}, nil)
}

// Notify meldt dat er iets veranderd is.
func (c *Client) Notify(ctx context.Context, conn Conn) error {
	return c.do(ctx, conn, http.MethodPost, "/api/v1/notify", map[string]any{"at": time.Now().UTC()}, nil)
}

// Notifier bundelt wijzigingen: hoogstens één melding per Delay, aan elke
// gekoppelde backup server, met een paar nieuwe pogingen bij een fout. De
// backup servers halen daarnaast periodiek alles op, dus een gemiste
// melding kost alleen vertraging.
type Notifier struct {
	Client *Client
	Delay  time.Duration
	once   sync.Once
	kick   chan struct{}
}

// Changed zegt dat er iets veranderd is. Blokkeert nooit.
func (n *Notifier) Changed() {
	if n == nil {
		return
	}
	n.once.Do(func() {
		n.kick = make(chan struct{}, 1)
		go n.loop()
	})
	select {
	case n.kick <- struct{}{}:
	default:
	}
}

func (n *Notifier) loop() {
	delay := n.Delay
	if delay <= 0 {
		delay = 2 * time.Second
	}
	for range n.kick {
		time.Sleep(delay)
		// Wat in de tussentijd binnenkwam, zit in deze melding.
		select {
		case <-n.kick:
		default:
		}
		list, err := n.Client.Manager.List()
		if err != nil {
			continue
		}
		var wg sync.WaitGroup
		for _, conn := range list {
			if !conn.Connected() {
				continue
			}
			wg.Add(1)
			go func(conn Conn) {
				defer wg.Done()
				for try := 0; try < 4; try++ {
					ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
					err := n.Client.Notify(ctx, conn)
					cancel()
					if err == nil {
						return
					}
					time.Sleep(time.Duration(1<<try) * 2 * time.Second)
				}
			}(conn)
		}
		wg.Wait()
	}
}
