using Infrastructure;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Algo.Request;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using SqlSugar;

namespace OpenAuth.App.ServiceApp;

public class AlgoInstanceServiceApp : SqlSugarBaseApp<LasaAlgoInstance, SugarDbContext>
{
    public AlgoInstanceServiceApp(ISugarUnitOfWork<SugarDbContext> unitWork,
        ISimpleClient<LasaAlgoInstance> repository, IAuth auth) : base(unitWork, repository, auth)
    {
    }

    public async Task<Response<bool>> AddAlgoInstance(LasaAlgoInstance info)
    {
        info.Id = Guid.NewGuid().ToString();
        if (await Repository.InsertAsync(info))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "添加成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "添加失败"
        };
    }

    public async Task<Response<bool>> DeleteAlgoInstance(string id)
    {
        if (await Repository.DeleteByIdAsync(id))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "删除成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "删除失败"
        };
    }

    public async Task<Response<bool>> UpdateAlgoInstance(LasaAlgoInstance info)
    {
        // todo 关于会更新空值问题
        if (await Repository.UpdateAsync(info))
        {
            return new Response<bool>
            {
                Result = true,
                Message = "修改成功"
            };
        }

        return new Response<bool>
        {
            Result = false,
            Message = "修改失败"
        };
    }

    public async Task<Response<PageInfo<List<LasaAlgoInstance>>>> GetAlgoInstanceList(AlgoInstancePageRequest req)
    {
        RefAsync<int> totalCount = 0;
        var page = await Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(req.key), x => x.Name.Contains(req.key))
            .ToPageListAsync(req.page, req.limit, totalCount);

        return new Response<PageInfo<List<LasaAlgoInstance>>>
        {
            Result = new PageInfo<List<LasaAlgoInstance>>
            {
                Items = page,
                Total = totalCount.Value
            }
        };
    }

    public async Task<Response<LasaAlgoInstance>> GetAlgoInstance(string id)
    {
        return new Response<LasaAlgoInstance>
        {
            Result = await Repository.GetByIdAsync(id)
        };
    }
}