using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using SkyArtShop.Data;
using SkyArtShop.Models;

namespace SkyArtShop.Services;

public class SqlDataService
{
	private readonly SkyArtShopDbContext _context;

	public SqlDataService(SkyArtShopDbContext context)
	{
		_context = context;
	}

	public async Task<List<T>> GetAllAsync<T>() where T : class
	{
		return await _context.Set<T>().ToListAsync();
	}

	public async Task<T?> GetByIdAsync<T>(string id) where T : class
	{
		return await _context.Set<T>().FindAsync(id);
	}

	public async Task<T> InsertAsync<T>(T entity) where T : class
	{
		_context.Set<T>().Add(entity);
		await _context.SaveChangesAsync();
		return entity;
	}

	public async Task<T> UpdateAsync<T>(T entity) where T : class
	{
		_context.Set<T>().Update(entity);
		await _context.SaveChangesAsync();
		return entity;
	}

	public async Task DeleteAsync<T>(string id) where T : class
	{
		T val = await GetByIdAsync<T>(id);
		if (val != null)
		{
			_context.Set<T>().Remove(val);
			await _context.SaveChangesAsync();
		}
	}

	public async Task<AdminUser?> GetUserByEmailAsync(string email)
	{
		return await _context.AdminUsers.FirstOrDefaultAsync((AdminUser u) => u.Email.ToLower() == email.ToLower());
	}

	public async Task<List<Product>> GetFeaturedProductsAsync()
	{
		return await _context.Products.Where((Product p) => p.IsFeatured && p.IsActive).ToListAsync();
	}

	public async Task<List<Product>> GetTopSellersAsync(int count = 10)
	{
		return await (from p in _context.Products
			where p.IsTopSeller && p.IsActive
			orderby p.UnitsSold descending
			select p).Take(count).ToListAsync();
	}

	public async Task<Product?> GetProductBySlugAsync(string slug)
	{
		return await _context.Products.FirstOrDefaultAsync((Product p) => p.Slug == slug && p.IsActive);
	}

	public async Task<BlogPost?> GetBlogPostBySlugAsync(string slug)
	{
		return await _context.BlogPosts.FirstOrDefaultAsync((BlogPost b) => b.Slug == slug && b.IsPublished);
	}

	public async Task<Page?> GetPageBySlugAsync(string slug)
	{
		return await _context.Pages.FirstOrDefaultAsync((Page p) => p.PageSlug == slug && p.IsActive);
	}

	public async Task<SiteSettings?> GetSiteSettingsAsync()
	{
		return await _context.SiteSettings.FirstOrDefaultAsync();
	}

	public async Task<List<MenuItem>> GetActiveMenuItemsAsync()
	{
		return await (from m in _context.MenuItems
			where m.IsActive
			orderby m.DisplayOrder
			select m).ToListAsync();
	}
}
