namespace TaxBaik.Application.Services;

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

public class TaxProfileService(ITaxProfileRepository repository)
{
    public async Task<int> CreateAsync(int clientId, string? businessType, string? businessRegistration = null,
        string? accountingMethod = null, DateTime? establishmentDate = null, CancellationToken ct = default)
    {
        if (clientId <= 0)
            throw new ValidationException("유효한 고객을 선택하세요.");
        if (string.IsNullOrWhiteSpace(businessType))
            throw new ValidationException("사업 유형을 입력하세요.");

        var profile = new TaxProfile
        {
            ClientId = clientId,
            BusinessType = businessType.Trim(),
            BusinessRegistration = string.IsNullOrWhiteSpace(businessRegistration) ? null : businessRegistration.Trim(),
            EstablishmentDate = establishmentDate,
            AccountingMethod = string.IsNullOrWhiteSpace(accountingMethod) ? null : accountingMethod.Trim(),
            TaxRiskLevel = "normal",
            CreatedAt = DateTime.UtcNow,
            UpdatedAt = DateTime.UtcNow
        };

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

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

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

    public async Task UpdateAsync(int profileId, string? businessType, string? accountingMethod,
        DateTime? nextFilingDueDate, string taxRiskLevel = "normal", CancellationToken ct = default)
    {
        var profile = await repository.GetByIdAsync(profileId, ct);
        if (profile == null)
            throw new ValidationException("세무 프로필을 찾을 수 없습니다.");

        if (!string.IsNullOrWhiteSpace(businessType))
            profile.BusinessType = businessType.Trim();
        if (!string.IsNullOrWhiteSpace(accountingMethod))
            profile.AccountingMethod = accountingMethod.Trim();
        profile.NextFilingDueDate = nextFilingDueDate;
        profile.TaxRiskLevel = taxRiskLevel;
        profile.UpdatedAt = DateTime.UtcNow;

        await repository.UpdateAsync(profile, ct);
    }

    public async Task<IEnumerable<TaxProfile>> GetHighRiskProfilesAsync(CancellationToken ct = default) =>
        await repository.GetByRiskLevelAsync("high", ct);

    public async Task<IEnumerable<TaxProfile>> GetUpcomingFilingDuesAsync(int daysAhead = 30, CancellationToken ct = default)
    {
        var startDate = DateTime.Today;
        var endDate = startDate.AddDays(daysAhead);
        return await repository.GetUpcomingFilingDuesAsync(startDate, endDate, ct);
    }
}
