using Microsoft.Data.SqlClient;
using Microsoft.SqlServer.Management.Smo;
using DBMigration.Models;

namespace DBMigration.Services
{
    public class MigrationService
    {
        private readonly DatabaseService _databaseService;

        public MigrationService()
        {
            _databaseService = new DatabaseService();
        }

        public void MigrateTable(DatabaseObject table, ConnectionInfo source, ConnectionInfo target)
        {
            using (var sourceConn = new SqlConnection(source.GetConnectionString()))
            using (var targetConn = new SqlConnection(target.GetConnectionString()))
            {
                sourceConn.Open();
                targetConn.Open();

                // 1. 테이블 생성 (인덱스 포함)
                ExecuteScript(table.Definition, targetConn);

                // 2. IDENTITY와 트리거 비활성화
                DisableIdentityAndTriggers(table, targetConn);

                // 3. 데이터 복사
                CopyData(table, sourceConn, targetConn);

                // 4. IDENTITY와 트리거 재활성화
                EnableIdentityAndTriggers(table, targetConn);

                // 5. 통계 업데이트
                UpdateStatistics(table, targetConn);
            }
        }

        private void ExecuteScript(string script, SqlConnection connection)
        {
            using (var cmd = new SqlCommand(script, connection))
            {
                cmd.ExecuteNonQuery();
            }
        }

        private void DisableIdentityAndTriggers(DatabaseObject table, SqlConnection connection)
        {
            var disableScript = $@"
                -- IDENTITY 비활성화
                SET IDENTITY_INSERT {table.FullName} ON;

                -- 트리거 비활성화
                DISABLE TRIGGER ALL ON {table.FullName};";

            ExecuteScript(disableScript, connection);
        }

        private void EnableIdentityAndTriggers(DatabaseObject table, SqlConnection connection)
        {
            var enableScript = $@"
                -- IDENTITY 활성화
                SET IDENTITY_INSERT {table.FullName} OFF;

                -- 트리거 활성화
                ENABLE TRIGGER ALL ON {table.FullName};";

            ExecuteScript(enableScript, connection);
        }

        private void CopyData(DatabaseObject table, SqlConnection source, SqlConnection target)
        {
            using (var cmd = new SqlCommand($"SELECT * FROM {table.FullName}", source))
            using (var reader = cmd.ExecuteReader())
            {
                using (var bulkCopy = new SqlBulkCopy(target))
                {
                    bulkCopy.DestinationTableName = table.FullName;
                    bulkCopy.WriteToServer(reader);
                }
            }
        }

        private void UpdateStatistics(DatabaseObject table, SqlConnection connection)
        {
            var updateStatsScript = $"UPDATE STATISTICS {table.FullName} WITH FULLSCAN;";
            ExecuteScript(updateStatsScript, connection);
        }
    }
}
