namespace TaxBaik.Application.Services;

using FluentValidation;
using TaxBaik.Application.DTOs;
using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;

public class AnnouncementService(IAnnouncementRepository repository, IValidator<AnnouncementDto> validator)
{
    public Task<IEnumerable<Announcement>> GetActiveAsync(CancellationToken ct = default)
        => repository.GetActiveAsync(ct);

    public Task<IEnumerable<Announcement>> GetAllAsync(CancellationToken ct = default)
        => repository.GetAllAsync(ct);

    public Task<Announcement?> GetByIdAsync(int id, CancellationToken ct = default)
        => repository.GetByIdAsync(id, ct);

    public Task<int> CreateAsync(AnnouncementDto dto, CancellationToken ct = default)
    {
        validator.ValidateAndThrow(dto);
        var entity = MapToEntity(dto);
        return repository.CreateAsync(entity, ct);
    }

    public Task UpdateAsync(AnnouncementDto dto, CancellationToken ct = default)
    {
        validator.ValidateAndThrow(dto);
        var entity = MapToEntity(dto);
        return repository.UpdateAsync(entity, ct);
    }

    public Task DeleteAsync(int id, CancellationToken ct = default)
        => repository.DeleteAsync(id, ct);

    private static Announcement MapToEntity(AnnouncementDto dto) => new()
    {
        Id = dto.Id,
        Title = dto.Title.Trim(),
        Content = string.IsNullOrWhiteSpace(dto.Content) ? null : dto.Content.Trim(),
        DisplayType = dto.DisplayType,
        IsActive = dto.IsActive,
        StartsAt = dto.StartsAt,
        EndsAt = dto.EndsAt,
        SortOrder = dto.SortOrder
    };
}
