package oidcsession

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"encoding/json"
	"errors"
	"fmt"
	"io"
)

type TokenBundle struct {
	AccessToken  string `json:"accessToken"`
	RefreshToken string `json:"refreshToken"`
	IDToken      string `json:"idToken,omitempty"`
}

type Cipher struct {
	aead cipher.AEAD
}

func NewCipher(key []byte) (*Cipher, error) {
	if len(key) != 32 {
		return nil, errors.New("OIDC session encryption key must be exactly 32 bytes")
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	aead, err := cipher.NewGCM(block)
	if err != nil {
		return nil, err
	}
	return &Cipher{aead: aead}, nil
}

func (c *Cipher) EncryptBundle(bundle TokenBundle, sessionID, gatewayUserID string) ([]byte, error) {
	return c.SealJSON(bundle, tokenAAD(sessionID, gatewayUserID))
}

func (c *Cipher) SealJSON(value any, aad []byte) ([]byte, error) {
	plaintext, err := json.Marshal(value)
	if err != nil {
		return nil, err
	}
	nonce := make([]byte, c.aead.NonceSize())
	if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
		return nil, err
	}
	return c.aead.Seal(nonce, nonce, plaintext, aad), nil
}

func (c *Cipher) DecryptBundle(encrypted []byte, sessionID, gatewayUserID string) (TokenBundle, error) {
	var bundle TokenBundle
	if err := c.OpenJSON(encrypted, tokenAAD(sessionID, gatewayUserID), &bundle); err != nil {
		return TokenBundle{}, err
	}
	if bundle.AccessToken == "" || bundle.RefreshToken == "" {
		return TokenBundle{}, errors.New("OIDC session token bundle is invalid")
	}
	return bundle, nil
}

func (c *Cipher) OpenJSON(encrypted, aad []byte, output any) error {
	if len(encrypted) <= c.aead.NonceSize() {
		return errors.New("OIDC session ciphertext is invalid")
	}
	nonce, ciphertext := encrypted[:c.aead.NonceSize()], encrypted[c.aead.NonceSize():]
	plaintext, err := c.aead.Open(nil, nonce, ciphertext, aad)
	if err != nil {
		return errors.New("OIDC session ciphertext authentication failed")
	}
	if err := json.Unmarshal(plaintext, output); err != nil {
		return errors.New("OIDC session ciphertext payload is invalid")
	}
	return nil
}

func tokenAAD(sessionID, gatewayUserID string) []byte {
	return []byte(fmt.Sprintf("easyai-gateway/oidc-session/v1\x00%s\x00%s", sessionID, gatewayUserID))
}
