using IWS5.Core.DTO;
using IWS5.Core.Enums;
using IWS5.Core.Exceptions;
using IWS5.Core.Models;
using IWS5.Core.Models.Request;
using IWS5.Core.Services;
using IWS5.DatabaseAccess.Interfaces;
using Serilog;

namespace IWS5.Services;

public class QueueService(IQueueRepository queueRepository, ILogger logger) : IQueueService
{
    public async Task<CodeResponse<ListQueuesResponseDTO>> ListQueues(ListQueuesRequest listQueuesRequest)
    {
        if (listQueuesRequest.ProcessId == 0)
        {
            logger.Error("ProcessId {processId} is required for ListQueues or should be more then 0", listQueuesRequest.ProcessId);
            return new CodeResponse<ListQueuesResponseDTO>(ResponseCode.BadRequest, "ProcessId is required for ListQueues or should be more then 0");
        }

        logger.Information("Starting ListQueues for User {UserName}", listQueuesRequest.UserName);
        var dataResponse = await queueRepository.GetAllowedQueues(listQueuesRequest);

        if (dataResponse.Count == 0)    
        {
            logger.Error("No queues found for User {UserName}", listQueuesRequest.UserName);
            return new CodeResponse<ListQueuesResponseDTO>(ResponseCode.OK);
        }

        var process = dataResponse.Select(queue => queue.Process).FirstOrDefault();

        var result = new ListQueuesResponseDTO
        {
            ProcessId = process.ProcessId,
            ProcessName = process.ProcessName,
            Queues = dataResponse.Select(q => new QueueListItem
            {
                QueueId = q.Id,
                QueueName = q.Queue,
                QueueAlias = q.Alias,
                Signable = q.Signable
            }).ToList().AsReadOnly()
        };

        logger.Information("Successfully retrieved queues for User {UserName}", listQueuesRequest.UserName);
        return new CodeResponse<ListQueuesResponseDTO>(ResponseCode.OK, null, result);
    }
}