using System.Linq.Expressions;
using Bogus;
using Microsoft.EntityFrameworkCore;
using Silk_Road_Api.DatabaseContext;

namespace Silk_Road_Api.Repositories;

public class ManufacturerRepository : Repository, IManufacturerRepository
{
    public ManufacturerRepository(SilkRoadApiContext context) : base(context)
    {
        //GenerateManufacturers(10);
    }

    public IQueryable<Manufacturer> GetManufacturers()
    {
        return AsQueryable<Manufacturer>();
    }

    public async Task<Manufacturer> GetManufacturer(int id)
    {
        return await GetAsync<Manufacturer>(id);
    }

    public async Task<int> GetManufacturerByName(string name)
    {
        return await AsQueryable<Manufacturer>().Where(x => x.name == name).Select(x => x.id).FirstOrDefaultAsync();
    }

    public void GenerateManufacturers(int n)
    {
        var manufacturers = new Faker<Manufacturer>()
            .RuleFor(m => m.name, f => f.Company.CompanyName())
            .RuleFor(m => m.address, f => f.Address.FullAddress())
            .RuleFor(m => m.contact, f => f.Internet.Email())
            .Generate(n);
        _context.AddRange(manufacturers);
        _context.SaveChanges();
    }

    public async Task<int> ExecuteCount(IQueryable<Manufacturer> query)
    {
        Expression<Func<IQueryable<Manufacturer>>> expression = () => query;
        return await _context.FromExpression(expression)
            .AsNoTracking()
            .Select(x => 1)
            .CountAsync()
            .ConfigureAwait(false);
    }
}