using System.Collections.Generic;
using System.Linq;
using Dapper;
using CncModels.Entity;
using CncRepository.Base;
using CncRepository.Interface;

namespace CncRepository.Impl
{
    public class ScreenFilterRepository : BusinessRepository, IScreenFilterRepository
    {
        public ScreenFilterRepository(string connectionString) : base(connectionString) { }

        public List<ScreenFilter> GetByScreenKey(string screenKey)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_screen_filter WHERE screen_key = @ScreenKey ORDER BY sort_order ASC";
                return conn.Query<ScreenFilter>(sql, new { ScreenKey = screenKey }).AsList();
            }
        }

        public int Create(ScreenFilter entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"INSERT INTO cnc_screen_filter (screen_key, filter_type, filter_value, is_default, sort_order) VALUES (@ScreenKey, @FilterType, @FilterValue, @IsDefault, @SortOrder); SELECT LAST_INSERT_ID();";
                return conn.ExecuteScalar<int>(sql, entity);
            }
        }

        public bool Update(ScreenFilter entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"UPDATE cnc_screen_filter SET screen_key = @ScreenKey, filter_type = @FilterType, filter_value = @FilterValue, is_default = @IsDefault, sort_order = @SortOrder WHERE id = @Id";
                int affected = conn.Execute(sql, entity);
                return affected > 0;
            }
        }

        public bool Delete(int id)
        {
            using (var conn = CreateConnection())
            {
                string sql = "DELETE FROM cnc_screen_filter WHERE id = @Id";
                return conn.Execute(sql, new { Id = id }) > 0;
            }
        }
    }
}
