package models

import (
	"context"
	"time"

	"github.com/mrhid6/vantage/admin/internal/db"
	"github.com/mrhid6/vantage/shared/license"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// SeedPlans inserts the tier table from shared/license on first boot.
//
// It uses $setOnInsert only: once a plan exists, staff edits to limits, features
// and Paddle IDs are authoritative and a redeploy must not stamp over them.
func SeedPlans(ctx context.Context) error {
	for _, tier := range []string{license.TierFree, license.TierProfessional, license.TierSelfHosted} {
		p, ok := license.PlanFor(tier)
		if !ok {
			continue
		}
		_, err := db.Admin("plans").UpdateOne(ctx,
			bson.M{"tier": tier},
			bson.M{"$setOnInsert": bson.M{
				"tier":       p.Tier,
				"name":       p.Name,
				"deployment": p.Deployment,
				"limits":     p.Limits,
				"features":   p.Features,
				"active":     true,
			}},
			options.UpdateOne().SetUpsert(true))
		if err != nil {
			return err
		}
	}
	return nil
}

// GetPlan reads a tier's authoritative definition.
func GetPlan(ctx context.Context, tier string) (*Plan, error) {
	var p Plan
	if err := db.Admin("plans").FindOne(ctx, bson.M{"tier": tier}).Decode(&p); err != nil {
		return nil, err
	}
	return &p, nil
}

func now() time.Time { return time.Now().UTC() }
