using BBM.ChatGLM.ChatSession.Aggregates;
using BBM.ChatGLM.ChatSession.Repositorys;
using BBM.ChatGLM.Dtos;
using BBM.ChatGLM.User.Repositorys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BBM.ChatGLM.FreeSqlRepository
{
    public class ChatSessionFreeSqlRepository : FreeSqlBasicRepository, IChatSessionFreeSqlRepository
    {
        public async Task<List<ChatSessionDto>> PageAsync(string filter, int pageSize, int pageIndex, Guid? tenantId)
        {
            var sql = "SELECT CS.\"Id\" AS \"Id\", UR.\"UserName\" AS \"UserName\", UR.\"Name\" AS \"Name\", CS.\"Content\" AS \"Content\", CS.\"CreationTime\" AS \"CreationTime\" FROM \"ChatSessions\" AS CS";
            sql += " LEFT JOIN \"AbpUsers\" AS UR ON CS.\"UserId\" = UR.\"Id\"";
            sql += " WHERE UR.\"IsDeleted\" = false";
            if (tenantId != null)
            {
                sql += $" AND UR.\"TenantId\" = '{tenantId}'";
            }
            if (!string.IsNullOrWhiteSpace(filter))
            {
                sql += $" AND (UR.\"UserName\" LIKE '{filter}%' OR UR.\"Name\" LIKE '{filter}%' OR CS.\"Content\" LIKE '{filter}%')";
            }
            sql += " ORDER BY CS.\"CreationTime\" ASC";
            sql += $" LIMIT {pageSize} OFFSET {pageIndex * pageSize}";
            return await FreeSql.Select<ChatSessionDto>().WithSql(sql).ToListAsync();
        }

        public async Task<long> CountAsync(string filter, Guid? tenantId)
        {
            var sql = "SELECT COUNT(CS.\"Id\") AS \"Count\" FROM \"ChatSessions\" AS CS";
            sql += " LEFT JOIN \"AbpUsers\" AS UR ON CS.\"UserId\" = UR.\"Id\"";
            sql += " WHERE UR.\"IsDeleted\" = FALSE";
            if (tenantId != null)
            {
                sql += $" AND UR.\"TenantId\" = '{tenantId}'";
            }
            if (!string.IsNullOrWhiteSpace(filter))
            {
                sql += $" AND (UR.\"UserName\" LIKE '{filter}%' OR UR.\"Name\" LIKE '{filter}%' OR CS.\"Content\" LIKE '{filter}%')";
            }
            var data = await FreeSql.Select<CountDto>().WithSql(sql).FirstAsync();
            return data.Count;
        }
    }
}
