package services

import (
	"context"
	"time"

	"github.com/mrhid6/vantage/server/internal/db"
	"github.com/mrhid6/vantage/server/internal/models"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func GetInstanceOIDC(instanceID string) (*models.InstanceOIDC, error) {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	var o models.InstanceOIDC
	err := db.Col("instance_oidc").FindOne(ctx, bson.M{"instance_id": instanceID}).Decode(&o)
	if err != nil {
		return nil, err
	}
	return &o, nil
}

func GetInstanceOIDCSecret(instanceID string) (string, error) {
	o, err := GetInstanceOIDC(instanceID)
	if err != nil {
		return "", err
	}
	return decryptString(o.ClientSecretEnc)
}

func SaveInstanceOIDC(instanceID, issuer, clientID, clientSecret string, enabled bool) error {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	set := bson.M{
		"instance_id": instanceID, "issuer": issuer, "client_id": clientID,
		"enabled": enabled, "updated_at": time.Now(),
	}
	if clientSecret != "" {
		enc, err := encryptString(clientSecret)
		if err != nil {
			return err
		}
		set["client_secret_enc"] = enc
	}
	_, err := db.Col("instance_oidc").UpdateOne(ctx,
		bson.M{"instance_id": instanceID}, bson.M{"$set": set},
		options.UpdateOne().SetUpsert(true))
	return err
}
