using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Fengling.Platform.Domain.AggregatesModel.TenantAggregate;
using Fengling.Platform.Infrastructure;
using Microsoft.EntityFrameworkCore;

namespace Fengling.Console.Repositories;

public class TenantRepository(PlatformDbContext context,ApplicationDbContext identityDbContext) : ITenantRepository
{
    public async Task<Tenant?> GetByIdAsync(long id)
    {
        return await context.Tenants.FindAsync(id);
    }

    public async Task<Platform.Domain.AggregatesModel.TenantAggregate.Tenant?> GetByTenantCodeAsync(string tenantCode)
    {
        return await context.Tenants.FirstOrDefaultAsync(t => t.TenantCode == tenantCode);
    }

    public async Task<IEnumerable<Tenant>> GetAllAsync()
    {
        return await context.Tenants.ToListAsync();
    }

    public async Task<IEnumerable<Tenant>> GetPagedAsync(int page, int pageSize, string? name = null,
        string? tenantCode = null, TenantStatus? status = null)
    {
        var query = context.Tenants.AsQueryable();

        if (!string.IsNullOrEmpty(name))
        {
            query = query.Where(t => t.Name.Contains(name));
        }

        if (!string.IsNullOrEmpty(tenantCode))
        {
            query = query.Where(t => t.TenantCode.Contains(tenantCode));
        }

        if (status.HasValue)
        {
            query = query.Where(t => t.Status == status);
        }

        return await query
            .OrderByDescending(t => t.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    public async Task<int> CountAsync(string? name = null, string? tenantCode = null, TenantStatus? status = null)
    {
        var query = context.Tenants.AsQueryable();

        if (!string.IsNullOrEmpty(name))
        {
            query = query.Where(t => t.Name.Contains(name));
        }

        if (!string.IsNullOrEmpty(tenantCode))
        {
            query = query.Where(t => t.TenantCode.Contains(tenantCode));
        }

        if (status.HasValue)
        {
            query = query.Where(t => t.Status == status);
        }

        return await query.CountAsync();
    }

    public async Task AddAsync(Tenant tenant)
    {
        context.Tenants.Add(tenant);
        await context.SaveChangesAsync();
    }

    public async Task UpdateAsync(Tenant tenant)
    {
        context.Tenants.Update(tenant);
        await context.SaveChangesAsync();
    }

    public async Task DeleteAsync(Tenant tenant)
    {
        context.Tenants.Remove(tenant);
        await context.SaveChangesAsync();
    }

    public async Task<int> GetUserCountAsync(TenantId tenantId)
    {
        return await identityDbContext.Users.CountAsync(u => u.TenantInfo.TenantId == tenantId && !u.IsDeleted);
    }
}
