namespace TaxBaik.Application.Services;

using TaxBaik.Domain.Entities;
using TaxBaik.Domain.Interfaces;

public class TaxFilingScheduleService(ITaxFilingScheduleRepository repository)
{
    public async Task<int> CreateAsync(int clientId, string filingType, DateTime dueDate, int filingYear,
        int? assignedToId = null, CancellationToken ct = default)
    {
        if (clientId <= 0)
            throw new ValidationException("유효한 고객을 선택하세요.");
        if (string.IsNullOrWhiteSpace(filingType))
            throw new ValidationException("신고 유형을 입력하세요.");
        if (dueDate < DateTime.Today)
            throw new ValidationException("마감일은 오늘 이후여야 합니다.");

        var schedule = new TaxFilingSchedule
        {
            ClientId = clientId,
            FilingType = filingType.Trim(),
            DueDate = dueDate,
            FilingYear = filingYear,
            Status = "pending",
            AssignedToId = assignedToId,
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

        return await repository.CreateAsync(schedule, ct);
    }

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

    public async Task<IEnumerable<TaxFilingSchedule>> GetAllAsync(CancellationToken ct = default) =>
        await repository.GetAllAsync(ct);

    public async Task<IEnumerable<TaxFilingSchedule>> GetByClientIdAsync(int clientId, CancellationToken ct = default) =>
        await repository.GetByClientIdAsync(clientId, ct);

    public async Task<IEnumerable<TaxFilingSchedule>> GetUpcomingDuesAsync(int daysAhead = 30, CancellationToken ct = default) =>
        await repository.GetUpcomingDuesAsync(daysAhead, ct);

    public async Task MarkCompletedAsync(int id, CancellationToken ct = default) =>
        await repository.MarkCompletedAsync(id, ct);

    public async Task<int> GetPendingCountAsync(CancellationToken ct = default)
    {
        var pending = await repository.GetByStatusAsync("pending", ct);
        return pending.Count();
    }
}
