using System;
using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncModels.Dto;
using CncModels.Dto.Log;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl
{
    public class SystemLogRepository : LogRepository, ISystemLogRepository
    {
        public SystemLogRepository(string connectionString) : base(connectionString) { }

        public PagedResult<SystemLogListItem> GetList(SystemLogQuery query)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"SELECT id, created_at, log_level, source, message, stack_trace, extra_data
                                FROM log_system
                                WHERE 1=1";
                string countSql = @"SELECT COUNT(*) FROM log_system WHERE 1=1";
                if (!string.IsNullOrEmpty(query.LogLevel)) { sql += " AND log_level = @LogLevel"; countSql += " AND log_level = @LogLevel"; }
                if (!string.IsNullOrEmpty(query.Source)) { sql += " AND source = @Source"; countSql += " AND source = @Source"; }
                if (!string.IsNullOrEmpty(query.StartDate)) { sql += " AND created_at >= @Start"; countSql += " AND created_at >= @Start"; }
                if (!string.IsNullOrEmpty(query.EndDate)) { sql += " AND created_at <= @End"; countSql += " AND created_at <= @End"; }
                if (!string.IsNullOrEmpty(query.Keyword)) { sql += " AND message LIKE @Keyword"; countSql += " AND message LIKE @Keyword"; }
                var p = new DynamicParameters();
                p.Add("LogLevel", query.LogLevel);
                p.Add("Source", query.Source);
                p.Add("Start", query.StartDate);
                p.Add("End", query.EndDate);
                p.Add("Keyword", "%" + query.Keyword + "%");
                int offset = (query.Page - 1) * query.PageSize;
                p.Add("Limit", query.PageSize);
                p.Add("Offset", offset);
                sql += " ORDER BY created_at DESC LIMIT @Limit OFFSET @Offset";
                var list = conn.Query<SystemLogListItem>(sql, p).AsList();
                int total = conn.ExecuteScalar<int>(countSql, p);
                return new PagedResult<SystemLogListItem> { Items = list, Total = total, Page = query.Page, PageSize = query.PageSize };
            }
        }

        public int Create(SystemLog entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"INSERT INTO log_system (log_level, source, message, stack_trace, extra_data, created_at)
                                VALUES (@LogLevel, @Source, @Message, @StackTrace, @ExtraData, @CreatedAt);";
                return conn.Execute(sql, entity);
            }
        }
    }
}
