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

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

        public MachineDailyStatus GetByMachineAndDate(int machineId, DateTime date)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_machine_daily_status WHERE machine_id = @MachineId AND production_date = @Date";
                return conn.QuerySingleOrDefault<MachineDailyStatus>(sql, new { MachineId = machineId, Date = date });
            }
        }

        public int Upsert(MachineDailyStatus entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"INSERT INTO cnc_machine_daily_status (machine_id, production_date, data_status, created_at, updated_at)
                                VALUES (@MachineId, @ProductionDate, @DataStatus, @CreatedAt, @UpdatedAt)
                                ON DUPLICATE KEY UPDATE data_status = @DataStatus, updated_at = @UpdatedAt";
                return conn.Execute(sql, entity);
            }
        }

        public List<MachineDailyStatus> GetByDate(DateTime date)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_machine_daily_status WHERE production_date = @Date";
                return conn.Query<MachineDailyStatus>(sql, new { Date = date }).AsList();
            }
        }

        public int CountByDateAndStatus(DateTime date, string dataStatus)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT COUNT(*) FROM cnc_machine_daily_status WHERE production_date = @Date AND data_status = @Status";
                return conn.ExecuteScalar<int>(sql, new { Date = date, Status = dataStatus });
            }
        }
    }
}
