using Fengling.Console.Datas;
using Fengling.Console.Models.Entities;
using Microsoft.EntityFrameworkCore;

namespace Fengling.Console.Repositories;

public class RoleRepository(ApplicationDbContext context) : IRoleRepository
{
    public async Task<ApplicationRole?> GetByIdAsync(long id)
    {
        return await context.Roles.FindAsync(id);
    }

    public async Task<ApplicationRole?> GetByNameAsync(string name)
    {
        return await context.Roles.FirstOrDefaultAsync(r => r.Name == name);
    }

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

    public async Task<IEnumerable<ApplicationRole>> GetPagedAsync(int page, int pageSize, string? name = null,
        string? tenantId = null)
    {
        var query = context.Roles.AsQueryable();

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

        if (!string.IsNullOrEmpty(tenantId))
        {
            query = query.Where(r => r.TenantId.ToString() == tenantId);
        }

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

    public async Task<int> CountAsync(string? name = null, string? tenantId = null)
    {
        var query = context.Roles.AsQueryable();

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

        if (!string.IsNullOrEmpty(tenantId))
        {
            query = query.Where(r => r.TenantId.ToString() == tenantId);
        }

        return await query.CountAsync();
    }

    public async Task AddAsync(ApplicationRole role)
    {
        context.Roles.Add(role);
        await context.SaveChangesAsync();
    }

    public async Task UpdateAsync(ApplicationRole role)
    {
        context.Roles.Update(role);
        await context.SaveChangesAsync();
    }

    public async Task DeleteAsync(ApplicationRole role)
    {
        context.Roles.Remove(role);
        await context.SaveChangesAsync();
    }
}