using System.Collections.Generic;
using System.Linq;
using CounterDrone.Core.Models;
using SQLite;

namespace CounterDrone.Core.Repository
{
    public class ScenarioRepository : BaseRepository<Scenario>
    {
        public ScenarioRepository(SQLiteConnection db) : base(db) { }

        public Scenario GetByScenarioNumber(string ScenarioNumber)
        {
            return Db.Table<Scenario>().FirstOrDefault(t => t.ScenarioNumber == ScenarioNumber);
        }

        public List<Scenario> Search(string keyword, string? dateFrom, string? dateTo, int offset, int limit, out int totalCount)
        {
            var query = Db.Table<Scenario>().AsQueryable();

            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(t => t.Name.Contains(keyword) || t.ScenarioNumber.Contains(keyword));

            if (!string.IsNullOrWhiteSpace(dateFrom))
                query = query.Where(t => t.CreatedAt.CompareTo(dateFrom) >= 0);

            if (!string.IsNullOrWhiteSpace(dateTo))
                query = query.Where(t => t.CreatedAt.CompareTo(dateTo) <= 0);

            totalCount = query.Count();
            return query.OrderByDescending(t => t.CreatedAt).Skip(offset).Take(limit).ToList();
        }
    }
}
