package store

import (
	"encoding/json"
	"os"
	"path/filepath"
)

// Session holds the server-issued token returned by POST /auth/poll.
// The ax server owns the full OIDC flow; the client only needs this token.
type Session struct {
	path  string
	Token string `json:"token"`
}

func LoadSession() (*Session, error) {
	sessionRoot, err := FindDataRoot(".local", "share")
	if err != nil {
		return nil, err
	}
	path := filepath.Join(sessionRoot, "session.json")
	data, err := os.ReadFile(path)
	if err != nil {
		if os.IsNotExist(err) {
			return &Session{path: path}, nil
		}
		return nil, err
	}
	var s Session
	if err := json.Unmarshal(data, &s); err != nil {
		return nil, err
	}
	s.path = path
	return &s, nil
}

func (s *Session) Save() error {
	if err := os.MkdirAll(filepath.Dir(s.path), 0700); err != nil {
		return err
	}
	data, err := json.MarshalIndent(s, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(s.path, data, 0600)
}

func (s *Session) ClearSession() error {
	err := os.Remove(s.path)
	if os.IsNotExist(err) {
		return nil
	}
	return err
}
