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

package updateserver

import (
	"context"
	"fmt"

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

const (
	MasterPackageName = "Master (Internal)"
	MasterPackageDesc = "Auto-created master package with unlimited access to all channels."
)

// EnsureMasterKey ensures that a master license package and key exist for the given owner.
// Returns the master key's raw key string only if it was just created (empty string otherwise).
func EnsureMasterKey(ctx context.Context, ownerID int64) (rawKey string, err error) {
	// Check if a master package already exists.
	pkgs, err := ListLicensePackages(ctx, ownerID)
	if err != nil {
		return "", err
	}

	var masterPkg *LicensePackage
	for _, pkg := range pkgs {
		if pkg.Name == MasterPackageName {
			masterPkg = pkg
			break
		}
	}

	// Create master package if it doesn't exist.
	if masterPkg == nil {
		masterPkg = &LicensePackage{
			OwnerID:      ownerID,
			Name:         MasterPackageName,
			Description:  MasterPackageDesc,
			DurationDays: 0, // lifetime
			MaxSites:     0, // unlimited
			RepoScope:    "all",
			IsActive:     true,
		}
		if err := CreateLicensePackage(ctx, masterPkg); err != nil {
			return "", fmt.Errorf("CreateLicensePackage: %w", err)
		}
	}

	// Check if a master key already exists for this package.
	keys, err := ListLicenseKeysByPackage(ctx, masterPkg.ID)
	if err != nil {
		return "", err
	}

	for _, key := range keys {
		if key.IsInternal {
			return "", nil // already exists, don't return raw key
		}
	}

	// Create the master key.
	masterKey := &LicenseKey{
		PackageID:  masterPkg.ID,
		OwnerID:    ownerID,
		IsInternal: true,
		IsActive:   true,
	}
	rawKey, err = CreateLicenseKey(ctx, masterKey)
	if err != nil {
		return "", fmt.Errorf("CreateLicenseKey: %w", err)
	}

	return rawKey, nil
}

// GetMasterKey returns the master key for an owner, if it exists.
func GetMasterKey(ctx context.Context, ownerID int64) (*LicenseKey, error) {
	key := new(LicenseKey)
	has, err := db.GetEngine(ctx).Where("owner_id = ? AND is_internal = ?", ownerID, true).Get(key)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return key, nil
}
