package auth

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"image"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
)

// ErrNoPhoto betekent dat Entra/Graph geen profielfoto heeft (404).
var ErrNoPhoto = errors.New("auth: geen Entra-profielfoto")

const (
	defaultGraphPhotoURL = "https://graph.microsoft.com/v1.0/me/photo/$value"
	graphPhotoMax        = 2 << 20
)

// GraphPhotoURL overschrijft de Graph-foto-URL (alleen voor tests).
// Leeg is de productie-URL op graph.microsoft.com.
func (e *Entra) photoURL() string {
	if e != nil && strings.TrimSpace(e.GraphPhotoURL) != "" {
		return strings.TrimSpace(e.GraphPhotoURL)
	}
	return defaultGraphPhotoURL
}

// FetchPhoto haalt de profielfoto op bij Microsoft Graph.
// Alleen de Graph-host (of de testhost in GraphPhotoURL) is toegestaan.
// 404 wordt ErrNoPhoto; andere fouten blijven een gewone error.
// De bytes zijn een geldige rasterafbeelding, begrensd tot graphPhotoMax.
func (e *Entra) FetchPhoto(ctx context.Context, accessToken string) ([]byte, error) {
	if e == nil || strings.TrimSpace(accessToken) == "" {
		return nil, ErrNoPhoto
	}
	rawURL := e.photoURL()
	if err := e.graphURLOK(rawURL); err != nil {
		return nil, err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer "+accessToken)
	req.Header.Set("Accept", "image/*")
	if e.UserAgent != "" {
		req.Header.Set("User-Agent", e.UserAgent)
	}
	res, err := e.graphClient().Do(req)
	if err != nil {
		return nil, fmt.Errorf("auth: Graph-foto: %w", err)
	}
	defer res.Body.Close()
	if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent {
		_, _ = io.Copy(io.Discard, io.LimitReader(res.Body, 64<<10))
		return nil, ErrNoPhoto
	}
	data, err := io.ReadAll(io.LimitReader(res.Body, graphPhotoMax+1))
	if err != nil {
		return nil, fmt.Errorf("auth: Graph-foto lezen: %w", err)
	}
	if len(data) > graphPhotoMax {
		return nil, fmt.Errorf("auth: Graph-foto te groot")
	}
	if res.StatusCode >= 400 {
		return nil, fmt.Errorf("auth: Graph-foto: %s", res.Status)
	}
	if _, _, err := image.Decode(bytes.NewReader(data)); err != nil {
		return nil, fmt.Errorf("auth: Graph-foto ongeldig: %w", err)
	}
	return data, nil
}

func (e *Entra) graphClient() *http.Client {
	base := e.HTTP
	if base == nil {
		base = &http.Client{Timeout: 15 * time.Second}
	}
	c := *base
	c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		if len(via) >= 5 {
			return fmt.Errorf("auth: te veel redirects")
		}
		return e.graphURLOK(req.URL.String())
	}
	return &c
}

func (e *Entra) graphURLOK(raw string) error {
	u, err := url.Parse(raw)
	if err != nil || u.Host == "" {
		return fmt.Errorf("auth: ongeldige Graph-URL")
	}
	want, err := url.Parse(e.photoURL())
	if err != nil || want.Host == "" {
		return fmt.Errorf("auth: ongeldige Graph-URL")
	}
	if !strings.EqualFold(u.Host, want.Host) {
		return fmt.Errorf("auth: Graph-foto alleen vanaf %s", want.Host)
	}
	if e.GraphPhotoURL == "" && u.Scheme != "https" {
		return fmt.Errorf("auth: Graph-foto moet HTTPS zijn")
	}
	if u.Scheme != "https" && u.Scheme != "http" {
		return fmt.Errorf("auth: ongeldige Graph-URL")
	}
	return nil
}
