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

namespace Indotalent.Features.Pipeline.SalesTeam.Cqrs;

public class CreateSalesTeamRequest
{
    public string? Name { get; set; }
    public string? Description { get; set; }
}

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

public record CreateSalesTeamCommand(CreateSalesTeamRequest Data) : IRequest<CreateSalesTeamResponse>;

public class CreateSalesTeamHandler : IRequestHandler<CreateSalesTeamCommand, CreateSalesTeamResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

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

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