package service

import (
	"fmt"

	"gorm.io/gorm"
)

// EnsureLogIndexes creates log_records indexes if missing.
func EnsureLogIndexes(db *gorm.DB) error {
	if db == nil {
		return nil
	}
	stmts := []string{
		`CREATE INDEX IF NOT EXISTS idx_log_records_created_at ON log_records(created_at);`,
		`CREATE INDEX IF NOT EXISTS idx_log_records_key_id ON log_records(key_id);`,
		`CREATE INDEX IF NOT EXISTS idx_log_records_model_name ON log_records(model_name);`,
		`CREATE INDEX IF NOT EXISTS idx_log_records_group ON log_records("group");`,
		`CREATE INDEX IF NOT EXISTS idx_log_records_status_code ON log_records(status_code);`,
		`CREATE INDEX IF NOT EXISTS idx_log_records_created_key ON log_records(created_at, key_id);`,
	}
	for _, stmt := range stmts {
		if err := db.Exec(stmt).Error; err != nil {
			return fmt.Errorf("ensure log indexes: %w", err)
		}
	}
	return nil
}
