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

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

        public SimTask GetByTaskNumber(string taskNumber)
        {
            return Db.Table<SimTask>().FirstOrDefault(t => t.TaskNumber == taskNumber);
        }

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

            if (!string.IsNullOrWhiteSpace(keyword))
                query = query.Where(t => t.Name.Contains(keyword) || t.TaskNumber.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();
        }
    }
}
