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

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

        public int Create(ProductionAdjustment entity)
        {
            using (var conn = CreateConnection())
            {
                string sql = @"INSERT INTO cnc_production_adjustment (target_table, target_id, field_name, old_value, new_value, reason, operator_ip, created_at)
                                VALUES (@TargetTable, @TargetId, @FieldName, @OldValue, @NewValue, @Reason, @OperatorIp, @CreatedAt);";
                return conn.Execute(sql, entity);
            }
        }

        public PagedResult<ProductionAdjustment> GetList(string targetTable, DateTime? startDate, DateTime? endDate, string keyword, int page, int pageSize)
        {
            using (var conn = CreateConnection())
            {
                string sqlBase = "SELECT * FROM cnc_production_adjustment WHERE 1=1";
                if (!string.IsNullOrEmpty(targetTable)) sqlBase += " AND target_table = @TargetTable";
                if (startDate.HasValue) sqlBase += " AND created_at >= @StartDate";
                if (endDate.HasValue) sqlBase += " AND created_at <= @EndDate";
                if (!string.IsNullOrEmpty(keyword)) sqlBase += " AND (CAST(target_id AS CHAR) LIKE @Keyword OR field_name LIKE @Keyword)";
                int offset = (page - 1) * pageSize;
                string sqlCount = "SELECT COUNT(*) FROM cnc_production_adjustment WHERE 1=1" +
                                  (string.IsNullOrEmpty(targetTable) ? string.Empty : " AND target_table = @TargetTable") +
                                  (startDate.HasValue ? " AND created_at >= @StartDate" : "") +
                                  (endDate.HasValue ? " AND created_at <= @EndDate" : "") +
                                  (!string.IsNullOrEmpty(keyword) ? " AND (CAST(target_id AS CHAR) LIKE @Keyword OR field_name LIKE @Keyword)" : "");
                string sqlPage = sqlBase + " ORDER BY created_at DESC LIMIT @Limit OFFSET @Offset";
                var param = new { TargetTable = targetTable, StartDate = startDate, EndDate = endDate, Keyword = ("%" + keyword + "%"), Limit = pageSize, Offset = offset };
                var items = conn.Query<ProductionAdjustment>(sqlPage, param).AsList();
                int total = conn.ExecuteScalar<int>(sqlCount, param);
                return new PagedResult<ProductionAdjustment> { Items = items, Total = total, Page = page, PageSize = pageSize };
            }
        }

        /// <inheritdoc/>
        public List<ProductionAdjustment> GetByTargetId(int targetId)
        {
            using (var conn = CreateConnection())
            {
                return conn.Query<ProductionAdjustment>(
                    "SELECT * FROM cnc_production_adjustment WHERE target_id = @TargetId ORDER BY created_at DESC",
                    new { TargetId = targetId }).AsList();
            }
        }
    }
}
