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

namespace Indotalent.Features.Multitenant.Tenant.Cqrs;

public class UpdateTenantRequest
{
    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 class UpdateTenantResponse
{
    public string? Id { get; set; }
    public bool Success { get; set; }
}

public record UpdateTenantCommand(UpdateTenantRequest Data) : IRequest<UpdateTenantResponse>;

public class UpdateTenantHandler : IRequestHandler<UpdateTenantCommand, UpdateTenantResponse>
{
    private readonly AppDbContext _context;

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

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

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

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

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

        entity.Name = request.Data.Name;
        entity.Description = request.Data.Description;
        entity.Street = request.Data.Street;
        entity.City = request.Data.City;
        entity.State = request.Data.State;
        entity.ZipCode = request.Data.ZipCode;
        entity.Country = request.Data.Country;
        entity.PhoneNumber = request.Data.PhoneNumber;
        entity.FaxNumber = request.Data.FaxNumber;
        entity.EmailAddress = request.Data.EmailAddress;
        entity.Website = request.Data.Website;
        entity.IsActive = request.Data.IsActive;

        await _context.SaveChangesAsync(cancellationToken);

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