package models

import (
	"fmt"

	"gorm.io/gorm"
)

var legacyTableRenames = []struct {
	legacy  string
	current string
}{
	{legacy: "senlin_agent_schema_migrations", current: "sa_schema_migrations"},
	{legacy: "senlin_agent_users", current: "sa_users"},
	{legacy: "senlin_agent_projects", current: "sa_projects"},
	{legacy: "senlin_agent_inbox_items", current: "sa_inbox_items"},
	{legacy: "senlin_agent_inbox_suggestions", current: "sa_inbox_suggestions"},
	{legacy: "senlin_agent_tasks", current: "sa_tasks"},
	{legacy: "senlin_agent_notes", current: "sa_notes"},
	{legacy: "senlin_agent_sources", current: "sa_sources"},
	{legacy: "senlin_agent_ai_expert_categories", current: "sa_ai_expert_categories"},
	{legacy: "senlin_agent_ai_experts", current: "sa_ai_experts"},
	{legacy: "senlin_agent_ai_sessions", current: "sa_ai_sessions"},
	{legacy: "senlin_agent_tags", current: "sa_tags"},
	{legacy: "senlin_agent_project_channels", current: "sa_project_channels"},
	{legacy: "senlin_agent_cron_plans", current: "sa_cron_plans"},
	{legacy: "senlin_agent_project_events", current: "sa_project_events"},
	{legacy: "senlin_agent_ai_keys", current: "sa_ai_keys"},
	{legacy: "senlin_agent_ai_call_logs", current: "sa_ai_call_logs"},
	{legacy: "senlin_agent_ai_rate_buckets", current: "sa_ai_rate_buckets"},
	{legacy: "senlin_agent_task_shares", current: "sa_task_shares"},
}

func renameLegacyTables(database *gorm.DB) error {
	migrator := database.Migrator()
	for _, table := range legacyTableRenames {
		if !migrator.HasTable(table.legacy) {
			continue
		}
		if migrator.HasTable(table.current) {
			return fmt.Errorf("cannot rename legacy table %s: target table %s already exists", table.legacy, table.current)
		}
		if err := migrator.RenameTable(table.legacy, table.current); err != nil {
			return fmt.Errorf("rename legacy table %s to %s: %w", table.legacy, table.current, err)
		}
	}
	return nil
}
