// Copyright 2026 Moko Consulting <hello@mokoconsulting.tech>
// SPDX-License-Identifier: GPL-3.0-or-later

package v1_27

import (
	"xorm.io/xorm"
)

// MigrateCustomFieldsToOrgLevel adds owner_id, scope to custom_field_def
// and renames issue_id to entity_id + adds entity_type in custom_field_value.
func MigrateCustomFieldsToOrgLevel(x *xorm.Engine) error {
	// Add new columns to custom_field_def
	type CustomFieldDef struct {
		OwnerID int64  `xorm:"INDEX NOT NULL DEFAULT 0 'owner_id'"`
		Scope   string `xorm:"VARCHAR(10) NOT NULL DEFAULT 'issue' 'scope'"`
	}
	if err := x.Sync(new(CustomFieldDef)); err != nil {
		return err
	}

	// Add entity_type and entity_id to custom_field_value
	type CustomFieldValue struct {
		EntityID   int64  `xorm:"INDEX NOT NULL DEFAULT 0 'entity_id'"`
		EntityType string `xorm:"VARCHAR(10) NOT NULL DEFAULT 'issue' 'entity_type'"`
	}
	if err := x.Sync(new(CustomFieldValue)); err != nil {
		return err
	}

	// Migrate existing data: copy issue_id to entity_id where entity_id is 0
	if _, err := x.Exec("UPDATE custom_field_value SET entity_id = issue_id WHERE entity_id = 0 AND issue_id != 0"); err != nil {
		return err
	}

	// Set issue_id default to 0 so new inserts don't require it
	_, err := x.Exec("ALTER TABLE custom_field_value MODIFY COLUMN issue_id bigint NOT NULL DEFAULT 0")
	return err
}
