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

namespace Indotalent.Features.Multitenant.Tenant.Cqrs;

public class CreateTenantRequest
{
    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; } = true;
}

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

public record CreateTenantCommand(CreateTenantRequest Data) : IRequest<CreateTenantResponse>;

public class CreateTenantHandler : IRequestHandler<CreateTenantCommand, CreateTenantResponse>
{
    private readonly AppDbContext _context;

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

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

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

        var entity = new Data.Entities.Tenant
        {
            Name = request.Data.Name,
            Description = request.Data.Description,
            Street = request.Data.Street,
            City = request.Data.City,
            State = request.Data.State,
            ZipCode = request.Data.ZipCode,
            Country = request.Data.Country,
            PhoneNumber = request.Data.PhoneNumber,
            FaxNumber = request.Data.FaxNumber,
            EmailAddress = request.Data.EmailAddress,
            Website = request.Data.Website,
            IsActive = request.Data.IsActive
        };

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

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