using AutoMapper;
using DbFirst.Application.Repositories;
using DbFirst.Contracts.Catalogs;
using DbFirst.Domain;
using DbFirst.Domain.Entities;
using MediatR;

namespace DbFirst.Application.Catalogs.Commands;

public class UpdateCatalogHandler : IRequestHandler<UpdateCatalogCommand, CatalogReadDto?>
{
    private readonly ICatalogRepository _repository;
    private readonly IMapper _mapper;

    public UpdateCatalogHandler(ICatalogRepository repository, IMapper mapper)
    {
        _repository = repository;
        _mapper = mapper;
    }

    public async Task<CatalogReadDto?> Handle(UpdateCatalogCommand request, CancellationToken cancellationToken)
    {
        var existing = await _repository.GetByIdAsync(request.Id, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        if (request.Dto.UpdateProcedure == CatalogUpdateProcedure.Update &&
            !string.Equals(existing.CatTitle, request.Dto.CatTitle, StringComparison.OrdinalIgnoreCase))
        {
            throw new InvalidOperationException("Titel kann nicht geändert werden.");
        }

        var entity = _mapper.Map<VwmyCatalog>(request.Dto);
        entity.Guid = request.Id;
        entity.AddedWho = existing.AddedWho;
        entity.AddedWhen = existing.AddedWhen;
        entity.ChangedWho = "system";
        entity.ChangedWhen = DateTime.UtcNow;

        var updated = await _repository.UpdateAsync(request.Id, entity, request.Dto.UpdateProcedure, cancellationToken);
        return updated == null ? null : _mapper.Map<CatalogReadDto>(updated);
    }
}
