package authsession

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"
)

type User struct {
	ID    string `json:"id"`
	Name  string `json:"name"`
	Email string `json:"email"`
}

type sessionEnvelope struct {
	User *User `json:"user"`
}

type Client struct {
	baseURL    string
	httpClient *http.Client
}

func NewClient(baseURL string) *Client {
	return &Client{
		baseURL: strings.TrimRight(baseURL, "/"),
		httpClient: &http.Client{
			Timeout: 5 * time.Second,
		},
	}
}

func (c *Client) GetUser(ctx context.Context, cookieHeader string) (*User, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/auth/get-session", nil)
	if err != nil {
		return nil, fmt.Errorf("create auth session request: %w", err)
	}

	if cookieHeader != "" {
		req.Header.Set("Cookie", cookieHeader)
	}

	res, err := c.httpClient.Do(req)
	if err != nil {
		return nil, fmt.Errorf("request auth session: %w", err)
	}
	defer res.Body.Close()

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

	var payload *sessionEnvelope
	if err := json.NewDecoder(res.Body).Decode(&payload); err != nil {
		return nil, fmt.Errorf("decode auth session: %w", err)
	}

	if payload == nil || payload.User == nil {
		return nil, nil
	}

	return payload.User, nil
}
