using Lab9.Context;
using Lab9.Models;

namespace Lab9.Repositories
{
    public class Repository : IRepository
    {
        private readonly NewsContext _context;

        public Repository(NewsContext context)
        {
            _context = context;
        }

        public IList<News> GetAllNews()
        {
            return _context.News.ToList();
        }

        public IList<News> GetAllNewsByCategory(string category)
        {
            return _context.News.Where(n => n.Category == category).ToList();
        }

        public IList<News> GetAllNewsByCategoryAndDate(string category, DateTime date)
        {
            return _context.News.Where(n => n.Category == category && n.Date == date).ToList();
        }

        public IList<News> GetAllNewsByDate(DateTime date)
        {
            return _context.News.Where(n => n.Date == date).ToList();
        }

        public News? GetNewsById(int id)
        {
            return _context.News.FirstOrDefault(n => n.Id == id);
        }

        public bool InsertNews(News news)
        {
            try
            {
                _context.News.Add(news);
                _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        public bool UpdateNews(News news)
        {
            try
            {
                _context.News.Update(news);
                _context.SaveChanges();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool ValidateUser(string username, string password)
        {
            return _context.Users.Any(u => u.Username == username && u.Password == password);
        }
    }
}
