using adas_core.Application.Repositories.Interfaces;
using adas_core.Application.Services.Interfaces;
using adas_core.Domain.Models.Filter;
using adas_core.Domain.Models.MongoModels;
using adas_core.Domain.Models.Responses;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;

namespace adas_core.Application.Services;

/// <summary>
/// Provides camera-related operations by coordinating the camera repository and point-of-care service, and logging diagnostic information.
/// </summary>
/// <remarks>
/// This service implements <see cref="ICameraService"/> and serves as the application-layer entry point for camera functionality.
/// </remarks>
public class CameraService(ILogger<CameraService> logger, ICameraRepository cameraRepository, IPointOfCareService pointOfCareService) : ICameraService
{
    private ICameraRepository _cameraRepository = cameraRepository;
    /// <summary>
    /// Retrieves a camera by its associated relay identifier from the camera repository.
    /// Returns null when no camera is found for the specified relay identifier.
    /// </summary>
    /// <param name="relayId">The unique identifier of the relay used to look up the camera.</param>
    /// <returns>A task that represents the asynchronous operation. The task result contains the matching <see cref="Camera"/>, or null if no camera is found.</returns>
    public Task<Camera?> GetById(ObjectId relayId)
    {
        return _cameraRepository.GetById(relayId);
    }
    /// <summary>
    /// Retrieves the list of cameras associated with the specified configuration relay identifiers.
    /// </summary>
    /// <param name="configurationRelayList">The list of configuration relay identifiers used to look up the corresponding cameras.</param>
    /// <returns>A <see cref="List{Camera}"/> containing the cameras linked to the provided configuration relay identifiers.</returns>
    public List<Camera> GetCameraInList(List<ObjectId> configurationRelayList)
    {
        return _cameraRepository.GetCameraInList(configurationRelayList);
    }

    /// <summary>
    /// Retrieves a paginated list of cameras, optionally filtered by whether they are currently in use, and resolves the in-use status for each returned camera using the point-of-care service.
    /// </summary>
    /// <param name="filter">The pagination filter that controls page number, page size, and optional filtering criteria such as the in-use flag.</param>
    /// <returns>A paginated response containing the requested cameras, the current page metadata, and the total document count; if no data is found, an empty paginated response is returned.</returns>
    public async Task<PaginationResponse<Camera>> GetPaginatedCameras(PaginationFilter filter)
    {
        var usedCameraIds = await pointOfCareService.FindAllIdCamerasInUse();

        var fluentQuery = _cameraRepository.GetPaginatedCameras(filter);

        if (filter.FilteredRequest?.InUse != null)
        {
            bool filterInUse = filter.FilteredRequest.InUse.Value;
            var filterBuilder = Builders<Camera>.Filter;

            var idFilter = filterInUse
                ? filterBuilder.In(c => c.Id, usedCameraIds)
                : filterBuilder.Not(filterBuilder.In(c => c.Id, usedCameraIds));

            fluentQuery.Filter = filterBuilder.And(fluentQuery.Filter, idFilter);
        }

        var count = await fluentQuery.CountDocumentsAsync();
        var data = await fluentQuery
            .Skip((filter.PageNumber - 1) * filter.PageSize)
            .Limit(filter.PageSize)
            .ToListAsync();

        if (data == null) return new PaginationResponse<Camera>([], filter.PageNumber, filter.PageSize, count);

        foreach (var camera in data)
        {
            if (camera == null) continue;

            bool isInUse = usedCameraIds.Contains(camera.Id);

            // Asignación mediante reflexión para el private set
            camera.GetType().GetProperty(nameof(Camera.InUse))
                ?.SetValue(camera, isInUse);
        }

        return new PaginationResponse<Camera>(data, filter.PageNumber, filter.PageSize, count);
    }

    /// <summary>
    /// Inserts a new camera into the system after validating its name and ensuring no duplicate exists.
    /// Throws an exception if the camera name is null or if another camera with the same name already exists.
    /// </summary>
    /// <param name="camera">The camera entity to insert.</param>
    /// <returns>The inserted camera, or null if the insertion did not return a result.</returns>
    /// <exception cref="System.Exception">Thrown when the camera name is null.</exception>
    /// <exception cref="System.Exception">Thrown when a camera with the same name already exists.</exception>
    public async Task<Camera?> InsertCamera(Camera camera)
    {
        if (camera.Name == null) throw new Exception("Camera name cannot be null");
        var cameraFound = await _cameraRepository.GetByName(camera.Name);
        if (cameraFound != null) throw new Exception($"Camera with name {camera.Name} already exists");
        return await _cameraRepository.InsertOneCamera(camera);
    }

    /// <summary>
    /// Updates an existing camera identified by its unique identifier, returning the updated entity if the operation succeeds.
    /// </summary>
    /// <param name="objectId">The unique identifier of the camera to update.</param>
    /// <param name="camera">The camera data containing the updated values.</param>
    /// <returns>A task that represents the asynchronous operation. The task result contains the updated <see cref="Camera"/>, or <c>null</c> if no camera with the specified identifier was found.</returns>
    public async Task<Camera?> UpdateCameraById(ObjectId objectId, Camera camera)
    {
        return await _cameraRepository.UpdateCameraAsync(objectId, camera);
    }

    /// <summary>
    /// Deletes a camera identified by the specified object identifier. Returns <c>false</c> when the camera is not found, and logs and returns <c>false</c> if an error occurs during the operation.
    /// </summary>
    /// <param name="objectId">The unique identifier of the camera to delete.</param>
    /// <returns><c>true</c> if the camera was successfully deleted; otherwise, <c>false</c>.</returns>
    public async Task<bool> DeleteCamera(ObjectId objectId)
    {
        try
        {
            var cameraToDelete = await _cameraRepository.GetById(objectId);
            if (cameraToDelete == null) return false;

            await _cameraRepository.DeleteAsync(cameraToDelete.Id);
            return true;
        }
        catch (Exception e)
        {
            logger.LogError(e, e.Message);
            return false;
        }

    }

    /// <summary>
    /// Retrieves a list of cameras matching the specified search text by delegating to the camera repository.
    /// </summary>
    /// <param name="textToSearch">The search text used to find cameras by name.</param>
    /// <returns>A task that represents the asynchronous operation, containing a list of <see cref="Camera"/> objects that match the search criteria.</returns>
    public async Task<List<Camera>> GetSearchByNameCameras(string textToSearch)
    {
        return await _cameraRepository.GetSearchByNameCameras(textToSearch);
    }
}