using System;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl.Log
{
    /// <summary>
    /// 日志库：log_collector_heartbeat 心跳仓储实现
    /// </summary>
    public class CollectorHeartbeatRepository : LogRepository, ICollectorHeartbeatRepository
    {
        public CollectorHeartbeatRepository(string connectionString) : base(connectionString) { }

        private const string SelectColumns = @"id as Id, service_id as ServiceId, status as Status, collect_address_id as CollectAddressId, last_collect_time as LastCollectTime, success_count as SuccessCount, fail_count as FailCount, uptime_seconds as UptimeSeconds, detail as Detail, created_at as CreatedAt";

        /// <summary>写入心跳</summary>
        public long Create(CollectorHeartbeat entity)
        {
            using (var conn = CreateConnection())
            {
                var sql = @"
                    INSERT INTO log_collector_heartbeat (
                        service_id, status, collect_address_id, last_collect_time, success_count, fail_count, uptime_seconds, detail, created_at
                    ) VALUES (
                        @ServiceId, @Status, @CollectAddressId, @LastCollectTime, @SuccessCount, @FailCount, @UptimeSeconds, @Detail, @CreatedAt
                    );
                    SELECT LAST_INSERT_ID();";
                return conn.ExecuteScalar<long>(sql, entity);
            }
        }

        /// <summary>获取最新心跳</summary>
        public CollectorHeartbeat GetLatest(string serviceId)
        {
            using (var conn = CreateConnection())
            {
                return conn.QueryFirstOrDefault<CollectorHeartbeat>($"SELECT {SelectColumns} FROM log_collector_heartbeat WHERE service_id = @ServiceId ORDER BY created_at DESC LIMIT 1", new { ServiceId = serviceId });
            }
        }

        /// <summary>清理过去的心跳记录（按日期）</summary>
        public int DeleteBeforeDate(DateTime date)
        {
            using (var conn = CreateConnection())
            {
                return conn.Execute(@"DELETE FROM log_collector_heartbeat WHERE created_at < @Date", new { Date = date });
            }
        }
    }
}
