package migrations

import (
	"errors"

	"github.com/pocketbase/dbx"
	"github.com/pocketbase/pocketbase/core"
	m "github.com/pocketbase/pocketbase/migrations"

	snaps "github.com/certimate-go/certimate/migrations/snaps/v0.4"
)

func init() {
	m.Register(func(app core.App) error {
		if err := app.DB().
			NewQuery("SELECT (1) FROM _migrations WHERE file={:file} LIMIT 1").
			Bind(dbx.Params{"file": "1763640000_m0.4.6.go"}).
			One(&struct{}{}); err == nil {
			return nil
		}

		tracer := NewTracer("v0.4.6")
		tracer.Printf("go ...")

		// adapt to new workflow data structure
		{
			walker := &snaps.WorkflowGraphWalker{}
			walker.Define(func(node *snaps.WorkflowNode) (_changed bool, _err error) {
				_changed = false
				_err = nil

				if node.Type != "bizDeploy" {
					return
				}

				nodeCfg := node.Data.Config

				switch nodeCfg["provider"] {
				case "1panel-site":
					{
						if providerCfg, ok := nodeCfg["providerConfig"].(map[string]any); ok {
							if providerCfg["websiteId"] != nil && providerCfg["websiteId"].(string) != "" {
								providerCfg["websiteMatchPattern"] = "specified"
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
								return
							}
						}
					}

				case "baotapanel-site":
					{
						if providerCfg, ok := nodeCfg["providerConfig"].(map[string]any); ok {
							if providerCfg["siteType"] == nil || providerCfg["siteType"].(string) == "other" {
								providerCfg["siteType"] = "any"
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
							}

							if providerCfg["siteNames"] == nil || providerCfg["siteNames"].(string) == "" {
								providerCfg["siteNames"] = providerCfg["siteName"]
								delete(providerCfg, "siteName")
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
							}

							if _changed {
								return
							}
						}
					}

				case "baotapanelgo-site":
					{
						if providerCfg, ok := nodeCfg["providerConfig"].(map[string]any); ok {
							if providerCfg["siteNames"] == nil || providerCfg["siteNames"].(string) == "" {
								providerCfg["siteType"] = "php"
								providerCfg["siteNames"] = providerCfg["siteName"]
								delete(providerCfg, "siteName")
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
								return
							}
						}
					}

				case "baotawaf-site":
					{
						if providerCfg, ok := nodeCfg["providerConfig"].(map[string]any); ok {
							if providerCfg["siteNames"] == nil || providerCfg["siteNames"].(string) == "" {
								providerCfg["siteNames"] = providerCfg["siteName"]
								delete(providerCfg, "siteName")
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
								return
							}
						}
					}

				case "ratpanel-site":
					{
						if providerCfg, ok := nodeCfg["providerConfig"].(map[string]any); ok {
							if providerCfg["siteNames"] == nil || providerCfg["siteNames"].(string) == "" {
								providerCfg["siteNames"] = providerCfg["siteName"]
								delete(providerCfg, "siteName")
								nodeCfg["providerConfig"] = providerCfg

								_changed = true
								return
							}
						}
					}

				case "safeline":
					{
						nodeCfg["provider"] = "safeline-site"

						_changed = true
						return
					}
				}

				return
			})

			// update collection `workflow`
			//   - migrate field `graphDraft` / `graphContent`
			{
				collection, err := app.FindCollectionByNameOrId("tovyif5ax6j62ur")
				if err != nil {
					return err
				}

				records, err := app.FindAllRecords(collection)
				if err != nil {
					return err
				}

				for _, record := range records {
					changed := false

					if ret, err := walker.Migrate(record, "graphDraft"); err != nil {
						return err
					} else {
						changed = changed || ret
					}

					if ret, err := walker.Migrate(record, "graphContent"); err != nil {
						return err
					} else {
						changed = changed || ret
					}

					if changed {
						if err := app.Save(record); err != nil {
							return err
						}

						tracer.Printf("record #%s in collection '%s' updated", record.Id, collection.Name)
					}
				}
			}

			// update collection `workflow_run`
			//   - migrate field `graph`
			{
				collection, err := app.FindCollectionByNameOrId("qjp8lygssgwyqyz")
				if err != nil {
					return err
				}

				records, err := app.FindAllRecords(collection)
				if err != nil {
					return err
				}

				for _, record := range records {
					changed := false

					if ret, err := walker.Migrate(record, "graph"); err != nil {
						return err
					} else {
						changed = changed || ret
					}

					if changed {
						if err := app.Save(record); err != nil {
							return err
						}

						tracer.Printf("record #%s in collection '%s' updated", record.Id, collection.Name)
					}
				}
			}

			// update collection `workflow_output`
			//   - migrate field `nodeConfig`
			{
				if _, err := app.DB().NewQuery("UPDATE workflow_output SET nodeConfig = REPLACE(nodeConfig, '\"provider\":\"safeline\"', '\"provider\":\"safeline-site\"') WHERE nodeConfig LIKE '%\"provider\":\"safeline\"%'").Execute(); err != nil {
					return err
				}

				if _, err := app.DB().NewQuery("UPDATE workflow_output SET nodeConfig = REPLACE(nodeConfig, '\"siteName\":', '\"siteNames\":')").Execute(); err != nil {
					return err
				}
			}
		}

		tracer.Printf("done")
		return nil
	}, func(app core.App) error {
		return errors.ErrUnsupported
	})
}
