package models

import (
	"context"
	"time"

	"gitea.hostxtra.co.uk/mrhid6/vantage/admin/internal/db"
	"gitea.hostxtra.co.uk/mrhid6/vantage/shared/license"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// SeedPlans inserts the six (deployment, tier) rows from shared/license on first
// boot.
//
// It uses $setOnInsert only: once a plan exists, staff edits to allowances,
// features and support level are authoritative and a redeploy must not stamp
// over them.
func SeedPlans(ctx context.Context) error {
	for _, deployment := range license.Deployments() {
		for _, tier := range license.Tiers() {
			p, ok := license.PlanFor(deployment, tier)
			if !ok {
				continue
			}
			_, err := db.Admin("plans").UpdateOne(ctx,
				bson.M{"deployment": deployment, "tier": tier},
				bson.M{"$setOnInsert": bson.M{
					"deployment":    p.Deployment,
					"tier":          p.Tier,
					"name":          p.Name,
					"base_limits":   p.Limits,
					"base_features": Features(p.Features).OrEmpty(),
					"support_level": p.SupportLevel,
					"active":        true,
				}},
				options.UpdateOne().SetUpsert(true))
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// GetPlan reads one pair's authoritative definition.
//
// It normalises the tier first, so a legacy self_hosted licence being reissued
// resolves to the plan that replaced it.
func GetPlan(ctx context.Context, deployment, tier string) (*Plan, error) {
	deployment, tier = license.NormaliseTier(deployment, tier)
	var p Plan
	if err := db.Admin("plans").FindOne(ctx,
		bson.M{"deployment": deployment, "tier": tier}).Decode(&p); err != nil {
		return nil, err
	}
	return &p, nil
}

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