using WorkTracker.Services.WorkDays;

namespace WorkTracker.Services.Exports;

public sealed class MonthlyTimesheetExcelExportService(
    IWorkDayService workDayService,
    IMonthlyTimesheetExcelExporter exporter,
    IWebHostEnvironment environment) : IMonthlyTimesheetExcelExportService
{
    private readonly IWorkDayService workDayService = workDayService;
    private readonly IMonthlyTimesheetExcelExporter exporter = exporter;
    private readonly IWebHostEnvironment environment = environment;

    public async Task<MonthlyTimesheetExcelFile> ExportAsync(int year, int month, bool includePreview, CancellationToken cancellationToken = default)
    {
        var templatePath = Path.Combine(environment.ContentRootPath, "Templates", "monthly-timesheet-template.xlsx");
        if (!File.Exists(templatePath))
        {
            throw new FileNotFoundException("Monthly timesheet template not found.", templatePath);
        }

        var timesheet = await workDayService.GetMonthlyTimesheetAsync(year, month, includePreview, cancellationToken);

        await using var templateStream = File.OpenRead(templatePath);
        var content = exporter.Export(timesheet, templateStream);

        return new MonthlyTimesheetExcelFile
        {
            FileName = $"timesheet-{year}-{month:00}.xlsx",
            Content = content
        };
    }
}