using IWS5.Core.Models.Request;
using IWS5.DatabaseAccess.Interfaces.Importer;
using IWS5.Importer.Abstractions.Services;
using Serilog;
using Serilog.Context;

namespace IWS5.Services.ImporterService;

public class WorkItemService : IWorkItemService
{
    private readonly IWorkItemRepository _workItemRepository;
    private readonly ILogger _logService;

    public WorkItemService(IWorkItemRepository workItemRepository, ILogger logService)
    {
        _workItemRepository = workItemRepository;
        _logService = logService;
    }

    /// <summary>
    /// Creates a new work item and logs the result.
    /// </summary>
    /// <param name="workItemRequest">Details of the work item to create.</param>
    /// <param name="createdBy">The user creating the work item.</param>
    public async Task CreateWorkItem(CreateWorkItemRequest workItemRequest, string createdBy)
    {
        if (workItemRequest is null)
            throw new ArgumentNullException(nameof(workItemRequest));

        try
        {
            using (LogContext.PushProperty("LogContext", nameof(WorkItemService)))
            {
                _logService.Information("Creating work item: {WorkItemName}", workItemRequest.WorkItemName);

                await _workItemRepository.InsertWorkItemAsync(workItemRequest, createdBy);

                _logService.Information("Successfully created work item: {WorkItemName}", workItemRequest.WorkItemName);
            }
        }
        catch (Exception ex)
        {
            LogCreationError(workItemRequest.WorkItemName, ex);
            throw;
        }
    }

    private void LogCreationError(string workItemName, Exception ex)
    {
        _logService.Error(ex, "Failed to create work item: {WorkItemName}", workItemName);
    }
}
