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

namespace CncRepository.Impl.Log
{
    /// <summary>
    /// 日志库：log_collect_raw 原始采集记录仓储实现
    /// </summary>
    public class CollectRawRepository : LogRepository, ICollectRawRepository
    {
        public CollectRawRepository(string connectionString) : base(connectionString) { }

        private const string SelectColumns = @"id as Id, collect_address_id as CollectAddressId, request_time as RequestTime, response_time as ResponseTime, response_duration as ResponseDuration, is_success as IsSuccess, status_code as StatusCode, raw_json as RawJson, error_message as ErrorMessage, created_at as CreatedAt";

        /// <summary>通过 Id 获取原始记录</summary>
        public CollectRaw GetById(long id)
        {
            using (var conn = CreateConnection())
            {
                return conn.QueryFirstOrDefault<CollectRaw>($"SELECT {SelectColumns} FROM log_collect_raw WHERE id = @Id", new { Id = id });
            }
        }

        /// <summary>按地址分页获取原始记录</summary>
        public PagedResult<CollectRaw> GetByAddressId(int collectAddressId, int page, int pageSize)
        {
            using (var conn = CreateConnection())
            {
                int skip = Math.Max(0, (page - 1) * pageSize);
                var items = conn.Query<CollectRaw>($"SELECT {SelectColumns} FROM log_collect_raw WHERE collect_address_id = @CollectAddressId ORDER BY created_at DESC LIMIT @PageSize OFFSET @Skip", new { CollectAddressId = collectAddressId, PageSize = pageSize, Skip = skip }).AsList();

                int total = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM log_collect_raw WHERE collect_address_id = @CollectAddressId", new { CollectAddressId = collectAddressId });
                return new PagedResult<CollectRaw> { Items = items.ToList(), Total = total, Page = page, PageSize = pageSize };
            }
        }

        /// <summary>获取某地址最新的一条原始采集记录</summary>
        public CollectRaw GetLatestByAddressId(int collectAddressId)
        {
            using (var conn = CreateConnection())
            {
                return conn.QueryFirstOrDefault<CollectRaw>($"SELECT {SelectColumns} FROM log_collect_raw WHERE collect_address_id = @CollectAddressId ORDER BY created_at DESC LIMIT 1", new { CollectAddressId = collectAddressId });
            }
        }

        /// <summary>分页获取所有原始记录</summary>
        public PagedResult<CollectRaw> GetAll(int page, int pageSize)
        {
            using (var conn = CreateConnection())
            {
                int skip = Math.Max(0, (page - 1) * pageSize);
                var items = conn.Query<CollectRaw>($"SELECT {SelectColumns} FROM log_collect_raw ORDER BY created_at DESC LIMIT @PageSize OFFSET @Skip", new { PageSize = pageSize, Skip = skip }).AsList();

                int total = conn.ExecuteScalar<int>(@"SELECT COUNT(1) FROM log_collect_raw");
                return new PagedResult<CollectRaw> { Items = items.ToList(), Total = total, Page = page, PageSize = pageSize };
            }
        }

        /// <summary>写入原始采集记录</summary>
        public long Create(CollectRaw entity)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"
                    INSERT INTO log_collect_raw (
                        collect_address_id, request_time, response_time, response_duration,
                        is_success, status_code, raw_json, error_message, created_at
                    ) VALUES (
                        @CollectAddressId, @RequestTime, @ResponseTime, @ResponseDuration,
                        @IsSuccess, @StatusCode, @RawJson, @ErrorMessage, @CreatedAt
                    );
                    SELECT LAST_INSERT_ID();";
                return conn.ExecuteScalar<long>(sql, entity);
            }
        }

        /// <summary>清理过期数据（按日期）</summary>
        public int DeleteBeforeDate(DateTime date)
        {
            using (var conn = CreateConnection())
            {
                return conn.Execute(@"DELETE FROM log_collect_raw WHERE created_at < @Date", new { Date = date });
            }
        }
    }
}
