using Indotalent.ConfigBackEnd.Exceptions;
using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Inventory.Warehouse.Cqrs;

public class UpdateWarehouseRequest
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public bool? SystemWarehouse { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public class UpdateWarehouseResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateWarehouseCommand(UpdateWarehouseRequest Data) : IRequest<UpdateWarehouseResponse>;

public class UpdateWarehouseHandler : IRequestHandler<UpdateWarehouseCommand, UpdateWarehouseResponse>
{
    private readonly AppDbContext _context;

    public UpdateWarehouseHandler(AppDbContext context) => _context = context;

    public async Task<UpdateWarehouseResponse> Handle(UpdateWarehouseCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.Warehouse
            .AnyAsync(x => x.Name == request.Data.Name && x.Id != request.Data.Id, cancellationToken);

        if (isExists)
        {
            throw new AlreadyExistsException("Warehouse", request.Data.Name ?? string.Empty);
        }

        var entity = await _context.Warehouse
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null)
        {
            return new UpdateWarehouseResponse { Id = request.Data.Id, Success = false };
        }

        entity.Name = request.Data.Name;
        entity.Description = request.Data.Description;
        entity.SystemWarehouse = request.Data.SystemWarehouse;
        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateWarehouseResponse
        {
            Id = entity.Id,
            Success = true
        };
    }
}