using Newtonsoft.Json.Linq;

using Sqler.SqlVersion.Entity;

using Vit.AutoTemp.DataProvider;
using Vit.Core.Util.ComponentModel.Data;

using Vitorm;

namespace App.Module.Sqler.Logical.SqlVersion
{

    public class SqlCode_DataProvider : DataProvider_Vitorm<SqlVersion_Code, DbContext>
    {
        public readonly string module;


        static DbContext CreateDbContext()
        {
            return Data.DataProvider<SqlVersion_Code>().CreateDbContext();
        }

        static Func<DbContext, IDbSet<SqlVersion_Code>> DbSetGenerator(string module)
        {
            return (dbContext) =>
            {
                var dbSet = dbContext.DbSet<SqlVersion_Code>();
                dbSet.ChangeTable(module);
                return dbSet;
            };
        }

        public SqlCode_DataProvider(string template, string module) : base(template, CreateDbContext, GetDbSet: DbSetGenerator(module))
        {
            this.module = module;
        }


        public int lastVersion
        {
            get
            {
                using var dbContext = CreateDbContext();
                var dbSet = GetDbSet(dbContext);
                var list = dbSet.Query().ToList();
                if (!list.Any()) return -1;
                return list.Max(m => m.version);
            }
        }


        public override ApiReturn delete(object sender, JObject arg)
        {
            throw new Exception("不可删除sql语句");
            return base.delete(sender, arg);
        }

        public override ApiReturn update(object sender, JObject model, string id)
        {
            if (SqlerHelp.sqlerConfig.GetByPath<bool?>("SqlVersion.Config.SqlCodeEditable") == false)
            {
                throw new Exception("不可修改sql语句");
            }

            return base.update(sender, model, id);
        }
    }




}
