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

namespace Indotalent.Features.Multitenant.Tenant.Cqrs;

public class TenantUserItemResponse
{
    public string? Id { get; set; }
    public string? UserId { get; set; }
    public string? Summary { get; set; }
    public bool IsActive { get; set; }
}

public class GetTenantByIdResponse
{
    public string? Id { get; set; }
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? Street { get; set; }
    public string? City { get; set; }
    public string? State { get; set; }
    public string? ZipCode { get; set; }
    public string? Country { get; set; }
    public string? PhoneNumber { get; set; }
    public string? FaxNumber { get; set; }
    public string? EmailAddress { get; set; }
    public string? Website { 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 List<TenantUserItemResponse> Users { get; set; } = new();
}

public record GetTenantByIdQuery(string Id) : IRequest<GetTenantByIdResponse?>;

public class GetTenantByIdHandler : IRequestHandler<GetTenantByIdQuery, GetTenantByIdResponse?>
{
    private readonly AppDbContext _context;

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

    public async Task<GetTenantByIdResponse?> Handle(GetTenantByIdQuery request, CancellationToken cancellationToken)
    {
        return await _context.Tenant
            .AsNoTracking()
            .Include(x => x.TenantUserList)
            .Where(x => x.Id == request.Id)
            .Select(x => new GetTenantByIdResponse
            {
                Id = x.Id,
                Name = x.Name,
                Description = x.Description,
                Street = x.Street,
                City = x.City,
                State = x.State,
                ZipCode = x.ZipCode,
                Country = x.Country,
                PhoneNumber = x.PhoneNumber,
                FaxNumber = x.FaxNumber,
                EmailAddress = x.EmailAddress,
                Website = x.Website,
                IsActive = x.IsActive,
                CreatedAt = x.CreatedAt,
                CreatedBy = x.CreatedBy,
                UpdatedAt = x.UpdatedAt,
                UpdatedBy = x.UpdatedBy,
                Users = x.TenantUserList
                    .OrderBy(u => u.Summary)
                    .Select(u => new TenantUserItemResponse
                    {
                        Id = u.Id,
                        UserId = u.UserId,
                        Summary = u.Summary,
                        IsActive = u.IsActive
                    }).ToList()
            })
            .FirstOrDefaultAsync(cancellationToken);
    }
}