package migrate_record

import (
	"github.com/pingcap/dbaas/billing2/db/entity"
	"gorm.io/gorm"
)

// 2026-08-12-billing2-invoices-invoice-date-index
//
// Adds a standalone index on billing2_invoices.invoice_date so the
// /api/v1/billing/invoices endpoint can ORDER BY invoice_date without
// a table scan. The composite index user_date (tenant_id, invoice_date)
// already exists but the ops list query filters by invoice_date range
// alone, which cannot use the tenant_id-led index efficiently.
//
// Fresh DBs get the index from the entity tag (db/entity/entity.go:376),
// warm DBs are patched here.
var _ = AddMigrateRecord(
	"2026-08-12-billing2-invoices-invoice-date-index",
	func(db *gorm.DB) error {
		// AutoMigrate picks up the entity tag change for fresh DBs.
		if err := db.AutoMigrate(entity.Models...); err != nil {
			return err
		}

		// Warm DBs: guard with information_schema to avoid duplicate DDL.
		var idxCount int
		if err := db.Raw(
			"SELECT COUNT(*) FROM information_schema.statistics "+
				"WHERE table_schema = DATABASE() AND table_name = ? AND index_name = ?",
			"billing2_invoices", "idx_billing2_invoices_invoice_date",
		).Scan(&idxCount).Error; err != nil {
			return err
		}
		if idxCount == 0 {
			if err := db.Exec(
				"CREATE INDEX `idx_billing2_invoices_invoice_date` " +
					"ON `billing2_invoices` (`invoice_date`)",
			).Error; err != nil {
				return err
			}
		}
		return nil
	},
)
