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 WorkerDailySummaryRepository : BusinessRepository, IWorkerDailySummaryRepository
    {
        public WorkerDailySummaryRepository(string connectionString) : base(connectionString) { }

        public WorkerDailySummary GetByWorkerAndDate(int workerId, DateTime date)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_worker_daily_summary WHERE worker_id = @WorkerId AND production_date = @Date";
                return conn.QuerySingleOrDefault<WorkerDailySummary>(sql, new { WorkerId = workerId, Date = date });
            }
        }

        public List<WorkerDailySummary> GetByDateRange(DateTime startDate, DateTime endDate)
        {
            using (var conn = CreateConnection())
            {
                string sql = "SELECT * FROM cnc_worker_daily_summary WHERE production_date BETWEEN @Start AND @End";
                return conn.Query<WorkerDailySummary>(sql, new { Start = startDate, End = endDate }).AsList();
            }
        }

        public int Upsert(WorkerDailySummary entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"INSERT INTO cnc_worker_daily_summary (worker_id, production_date, total_quantity, machine_count, program_count, is_adjusted, adjusted_quantity, created_at, updated_at)
                                VALUES (@WorkerId, @ProductionDate, @TotalQuantity, @MachineCount, @ProgramCount, @IsAdjusted, @AdjustedQuantity, @CreatedAt, @UpdatedAt)
                                ON DUPLICATE KEY UPDATE total_quantity = @TotalQuantity, machine_count = @MachineCount, program_count = @ProgramCount, updated_at = @UpdatedAt";
                return conn.Execute(sql, entity);
            }
        }
    }
}
