using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using HoneyBox.Model.Models.Announcement;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace HoneyBox.Core.Services;

/// <summary>
/// 中奖公告服务实现（用户端）
/// </summary>
public class PrizeAnnouncementService : IPrizeAnnouncementService
{
    private readonly HoneyBoxDbContext _dbContext;
    private readonly ILogger<PrizeAnnouncementService> _logger;

    public PrizeAnnouncementService(
        HoneyBoxDbContext dbContext,
        ILogger<PrizeAnnouncementService> logger)
    {
        _dbContext = dbContext;
        _logger = logger;
    }

    /// <inheritdoc />
    public async Task<List<PrizeAnnouncementDto>> GetEnabledAnnouncementsAsync()
    {
        try
        {
            // 只返回启用状态的公告，按排序字段升序排列
            var announcements = await _dbContext.PrizeAnnouncements
                .Where(a => a.IsEnabled)
                .OrderBy(a => a.Sort)
                .Select(a => new PrizeAnnouncementDto
                {
                    Id = a.Id,
                    UserAvatar = a.UserAvatar ?? string.Empty,
                    UserName = a.UserName,
                    PrizeLevel = a.PrizeLevel,
                    PrizeName = a.PrizeName
                })
                .ToListAsync();

            return announcements;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to get enabled prize announcements");
            return new List<PrizeAnnouncementDto>();
        }
    }
}
