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

namespace Indotalent.Features.Multitenant.TenantUser.Cqrs;

public class UpdateTenantUserRequest
{
    public string? Id { get; set; }
    public string? TenantId { get; set; }
    public string? UserId { get; set; }
    public string? Summary { get; set; }
    public bool IsActive { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

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

public record UpdateTenantUserCommand(UpdateTenantUserRequest Data) : IRequest<UpdateTenantUserResponse>;

public class UpdateTenantUserHandler : IRequestHandler<UpdateTenantUserCommand, UpdateTenantUserResponse>
{
    private readonly AppDbContext _context;

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

    public async Task<UpdateTenantUserResponse> Handle(UpdateTenantUserCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.TenantUser
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

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

        entity.TenantId = request.Data.TenantId;
        entity.UserId = request.Data.UserId;
        entity.Summary = request.Data.Summary;
        entity.IsActive = request.Data.IsActive;

        await _context.SaveChangesAsync(cancellationToken);

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