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

namespace Indotalent.Features.Inventory.Warehouse.Cqrs;

public class CreateWarehouseRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
    public bool? SystemWarehouse { get; set; } = false;
}

public class CreateWarehouseResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
}

public record CreateWarehouseCommand(CreateWarehouseRequest Data) : IRequest<CreateWarehouseResponse>;

public class CreateWarehouseHandler : IRequestHandler<CreateWarehouseCommand, CreateWarehouseResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<CreateWarehouseResponse> Handle(CreateWarehouseCommand request, CancellationToken cancellationToken)
    {
        var isExists = await _context.Warehouse
            .AnyAsync(x => x.Name == request.Data.Name, cancellationToken);

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

        var entity = new Data.Entities.Warehouse
        {
            Name = request.Data.Name,
            Description = request.Data.Description,
            SystemWarehouse = request.Data.SystemWarehouse
        };

        _context.Warehouse.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreateWarehouseResponse
        {
            Id = entity.Id,
            Name = entity.Name
        };
    }
}