// Copyright 2026 Moko Consulting <hello@mokoconsulting.tech>
// SPDX-License-Identifier: GPL-3.0-or-later

package licensing

import (
	"context"

	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/models/db"
	"code.mokoconsulting.tech/MokoConsulting/MokoGitea/modules/json"
)

func init() {
	db.RegisterModel(new(ProductTier))
}

// ProductTier defines a licensing tier and its entitled repositories.
type ProductTier struct {
	ID         int64  `xorm:"pk autoincr"`
	TierKey    string `xorm:"VARCHAR(30) UNIQUE NOT NULL"`
	TierName   string `xorm:"VARCHAR(100) NOT NULL"`
	Repos      string `xorm:"TEXT"` // JSON array of repo names
	MaxDomains int    `xorm:"NOT NULL DEFAULT 1"`
	SortOrder  int    `xorm:"NOT NULL DEFAULT 0"`
}

func (ProductTier) TableName() string {
	return "product_tier"
}

// RepoList parses the Repos JSON field into a string slice.
func (t *ProductTier) RepoList() []string {
	var repos []string
	if t.Repos == "" {
		return repos
	}
	_ = json.Unmarshal([]byte(t.Repos), &repos)
	return repos
}

// GetProductTierByKey looks up a tier by its key (e.g. "pos", "suite").
func GetProductTierByKey(ctx context.Context, key string) (*ProductTier, error) {
	tier := new(ProductTier)
	has, err := db.GetEngine(ctx).Where("tier_key = ?", key).Get(tier)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return tier, nil
}

// GetAllProductTiers returns all tiers ordered by sort_order.
func GetAllProductTiers(ctx context.Context) ([]*ProductTier, error) {
	var tiers []*ProductTier
	return tiers, db.GetEngine(ctx).OrderBy("sort_order ASC").Find(&tiers)
}
