// 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/timeutil"
)

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

// LicenseAuditLog records status transitions and other license events.
type LicenseAuditLog struct {
	ID        int64              `xorm:"pk autoincr"`
	LicenseID int64              `xorm:"INDEX NOT NULL"`
	Action    string             `xorm:"VARCHAR(50) NOT NULL"` // status_change, tier_change, domain_activate, domain_deactivate
	OldValue  string             `xorm:"VARCHAR(100)"`
	NewValue  string             `xorm:"VARCHAR(100)"`
	CreatedAt timeutil.TimeStamp `xorm:"INDEX CREATED"`
}

func (LicenseAuditLog) TableName() string {
	return "license_audit_log"
}

// LogLicenseAudit records a license event.
func LogLicenseAudit(ctx context.Context, licenseID int64, action, oldVal, newVal string) error {
	entry := &LicenseAuditLog{
		LicenseID: licenseID,
		Action:    action,
		OldValue:  oldVal,
		NewValue:  newVal,
	}
	_, err := db.GetEngine(ctx).Insert(entry)
	return err
}

// GetAuditLog returns audit entries for a license, newest first.
func GetAuditLog(ctx context.Context, licenseID int64) ([]*LicenseAuditLog, error) {
	var entries []*LicenseAuditLog
	return entries, db.GetEngine(ctx).
		Where("license_id = ?", licenseID).
		OrderBy("created_at DESC").
		Find(&entries)
}
