package office

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"sync"
)

// documentKeyStore tracks OnlyOffice session keys per Nextcloud file id.
// The key stays stable while editors are active (refresh, co-editing) and rotates
// only after a successful save when the last editor closes (callback status 2).
type documentKeyStore struct {
	mu   sync.Mutex
	vers map[int64]uint64
}

func newDocumentKeyStore() *documentKeyStore {
	return &documentKeyStore{vers: make(map[int64]uint64)}
}

func (k *documentKeyStore) current(fileID int64) string {
	k.mu.Lock()
	defer k.mu.Unlock()
	ver := k.vers[fileID]
	if ver == 0 {
		ver = 1
		k.vers[fileID] = ver
	}
	return documentSessionKey(fileID, ver)
}

func (k *documentKeyStore) rotateAfterSave(fileID int64) {
	k.mu.Lock()
	defer k.mu.Unlock()
	ver := k.vers[fileID]
	if ver == 0 {
		ver = 1
	}
	k.vers[fileID] = ver + 1
}

func documentSessionKey(fileID int64, version uint64) string {
	h := sha256.Sum256([]byte(fmt.Sprintf("nc:%d:v%d", fileID, version)))
	return hex.EncodeToString(h[:16])
}
