using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations.Operations;
using Microsoft.EntityFrameworkCore.Update;

namespace IRaCIS.Core.Infra.EFCore;


/// <summary>
/// 迁移的时候，忽略显示外键的建立，增加灵活性，同时为了兼容之前dbfirst 一个字段关联多个表
/// </summary>
public class NoForeignKeyMigrationsSqlGenerator : SqlServerMigrationsSqlGenerator
{


    public NoForeignKeyMigrationsSqlGenerator(MigrationsSqlGeneratorDependencies dependencies, ICommandBatchPreparer commandBatchPreparer)
  : base(dependencies, commandBatchPreparer)
    {
    }

    protected override void Generate(Microsoft.EntityFrameworkCore.Migrations.Operations.CreateTableOperation operation, IModel? model, MigrationCommandListBuilder builder, bool terminate = true)
    {
        operation.ForeignKeys.Clear();

        base.Generate(operation, model, builder, terminate);
    }
    protected override void Generate(AddForeignKeyOperation operation, IModel? model, MigrationCommandListBuilder builder, bool terminate = true)
    {

    }

    protected override void Generate(DropForeignKeyOperation operation, IModel? model, MigrationCommandListBuilder builder, bool terminate = true)
    {
        // 忽略所有删除外键的操作
        // 不调用 base.Generate 来跳过生成删除外键的SQL
    }

    //忽略掉唯一约束
    protected override void Generate(CreateIndexOperation operation, IModel? model, MigrationCommandListBuilder builder, bool terminate = true)
    {
        //// 如果索引是唯一的，则忽略，不生成SQL语句
        //if (operation.IsUnique)
        //{
        //    return;  // 跳过唯一约束的索引创建
        //}

        //// 如果不是唯一索引，则继续生成
        //base.Generate(operation, model, builder, terminate);

        //// 获取表信息
        //var table = model?.FindEntityType(operation.Table);
        //if (table != null)
        //{
        //    // 跳过主键相关的索引（主键索引以主键列构建）
        //    var primaryKey = table.FindPrimaryKey();
        //    if (primaryKey != null && operation.Columns.SequenceEqual(primaryKey.Properties.Select(p => p.Name)))
        //    {
        //        base.Generate(operation, model, builder, terminate);
        //        return; // 生成主键相关的索引
        //    }
        //}

        // 检查是否是外键索引
        //var table = model?.FindEntityType(operation.Table);
        //if (table != null)
        //{
        //    foreach (var foreignKey in table.GetForeignKeys())
        //    {
        //        // 如果索引列和外键列相同，跳过生成
        //        if (operation.Columns.SequenceEqual(foreignKey.Properties.Select(p => p.Name)))
        //        {
        //            return; // 跳过生成外键索引
        //        }
        //    }
        //}


        if (IsForeignKeyIndex(operation, model))
            return;

        // 非外键索引，调用基类方法正常生成
        base.Generate(operation, model, builder, terminate);
    }
    private bool IsForeignKeyIndex(CreateIndexOperation operation, IModel? model)
    {
        var entity = model?
            .GetEntityTypes()
            .FirstOrDefault(e =>
                e.GetTableName() == operation.Table &&
                e.GetSchema() == operation.Schema);

        if (entity == null)
            return false;

        var tableId = StoreObjectIdentifier.Table(operation.Table, operation.Schema);

        foreach (var fk in entity.GetForeignKeys())
        {
            var cols = fk.Properties
                .Select(p => p.GetColumnName(tableId))
                .ToArray();

            if (cols.SequenceEqual(operation.Columns))
                return true;
        }

        return false;
    }


}
