package handlers

import (
	"api-service/internal/config"
	"api-service/internal/database"
	models "api-service/internal/models"
	"api-service/internal/models/qris"
	utils "api-service/internal/utils/filters"
	"context"
	"database/sql"
	"fmt"
	"log"
	"net"
	"net/http"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var (
	qrisdb       database.Service
	qrisonce     sync.Once
	qrisvalidate *validator.Validate
)

// Initialize the database connection and validator
func init() {
	qrisonce.Do(func() {
		qrisdb = database.New(config.LoadConfig())
		qrisvalidate = validator.New()
		qrisvalidate.RegisterValidation("qris_status", validateQrisStatus)
		if qrisdb == nil {
			log.Fatal("Failed to initialize database connection")
		}
	})
}

// Custom validation for qris status
func validateQrisStatus(fl validator.FieldLevel) bool {
	return models.IsValidStatus(fl.Field().String())
}

// QrisHandler handles qris services
type QrisHandler struct {
	db database.Service
}

// NewQrisHandler creates a new QrisHandler
func NewQrisHandler() *QrisHandler {
	return &QrisHandler{
		db: qrisdb,
	}
}

// GetQris godoc
// @Summary Get qris with pagination and optional aggregation
// @Description Returns a paginated list of qriss with optional summary statistics
// @Tags Qris
// @Accept json
// @Produce json
// @Param limit query int false "Limit (max 100)" default(10)
// @Param offset query int false "Offset" default(0)
// @Param include_summary query bool false "Include aggregation summary" default(false)
// @Param status query string false "Filter by status"
// @Param search query string false "Search in multiple fields"
// @Success 200 {object} qris.QrisGetResponse "Success response"
// @Failure 400 {object} models.ErrorResponse "Bad request"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /qris [get]
func (h *QrisHandler) GetQris(c *gin.Context) {
	// Parse pagination parameters
	limit, offset, err := h.parsePaginationParams(c)
	if err != nil {
		h.respondError(c, "Invalid pagination parameters", err, http.StatusBadRequest)
		return
	}

	// Parse filter parameters
	filter := h.parseFilterParams(c)
	includeAggregation := c.Query("include_summary") == "true"

	// Get database connection
	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	// Create context with timeout
	ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
	defer cancel()

	// Execute concurrent operations
	var (
		items         []qris.Qris
		total         int
		aggregateData *models.AggregateData
		wg            sync.WaitGroup
		errChan       = make(chan error, 3)
		mu            sync.Mutex
	)

	// Fetch total count
	wg.Add(1)
	go func() {
		defer wg.Done()
		if err := h.getTotalCount(ctx, dbConn, filter, &total); err != nil {
			mu.Lock()
			errChan <- fmt.Errorf("failed to get total count: %w", err)
			mu.Unlock()
		}
	}()

	// Fetch main data
	wg.Add(1)
	go func() {
		defer wg.Done()
		result, err := h.fetchQris(ctx, dbConn, filter, limit, offset)
		mu.Lock()
		if err != nil {
			errChan <- fmt.Errorf("failed to fetch data: %w", err)
		} else {
			items = result
		}
		mu.Unlock()
	}()

	// Fetch aggregation data if requested
	if includeAggregation {
		wg.Add(1)
		go func() {
			defer wg.Done()
			result, err := h.getAggregateData(ctx, dbConn, filter)
			mu.Lock()
			if err != nil {
				errChan <- fmt.Errorf("failed to get aggregate data: %w", err)
			} else {
				aggregateData = result
			}
			mu.Unlock()
		}()
	}

	// Wait for all goroutines
	wg.Wait()
	close(errChan)

	// Check for errors
	for err := range errChan {
		if err != nil {
			h.logAndRespondError(c, "Data processing failed", err, http.StatusInternalServerError)
			return
		}
	}

	// Build response
	meta := h.calculateMeta(limit, offset, total)
	response := qris.QrisGetResponse{
		Message: "Data qris berhasil diambil",
		Data:    items,
		Meta:    meta,
	}

	if includeAggregation && aggregateData != nil {
		response.Summary = aggregateData
	}

	c.JSON(http.StatusOK, response)
}

// GetQrisByID godoc
// @Summary Get Qris by ID
// @Description Returns a single qris by ID
// @Tags Qris
// @Accept json
// @Produce json
// @Param id path string true "Qris ID (Int serial4)"
// @Success 200 {object} qris.QrisGetByIDResponse "Success response"
// @Failure 400 {object} models.ErrorResponse "Invalid ID format"
// @Failure 404 {object} models.ErrorResponse "Qris not found"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /qris/{id} [get]
func (h *QrisHandler) GetQrisByID(c *gin.Context) {
	id := c.Param("id")

	// Validate Int ID format
	intID, err := strconv.Atoi(id)
	if err != nil {
		h.respondError(c, "Invalid ID format", err, http.StatusBadRequest)
		return
	}

	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
	defer cancel()

	item, err := h.getQrisByID(ctx, dbConn, intID)
	if err != nil {
		if err == sql.ErrNoRows {
			h.respondError(c, "Qris not found", err, http.StatusNotFound)
		} else {
			h.logAndRespondError(c, "Failed to get qris", err, http.StatusInternalServerError)
		}
		return
	}

	response := qris.QrisGetByIDResponse{
		Message: "qris details retrieved successfully",
		Data:    item,
	}

	c.JSON(http.StatusOK, response)
}

// GetQrisByIP godoc
// @Summary Get Qris by IP
// @Description Returns a single qris by IP
// @Tags Qris
// @Accept json
// @Produce json
// @Param ip path string true "IP address"
// @Success 200 {object} qris.QrisGetByIPResponse "Success response"
// @Failure 400 {object} models.ErrorResponse "Invalid IP address format"
// @Failure 404 {object} models.ErrorResponse "Qris not found"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /qris/ip/{ip} [get]
func (h *QrisHandler) GetQrisByIP(c *gin.Context) {
	ip := c.Param("ip")

	// Validate IP address format
	if net.ParseIP(ip) == nil {
		h.respondError(c, "Invalid IP address format", fmt.Errorf("invalid IP: %s", ip), http.StatusBadRequest)
		return
	}

	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
	defer cancel()

	items, err := h.getQrisByIP(ctx, dbConn, ip, c)
	if err != nil {
		if err == sql.ErrNoRows {
			h.respondError(c, "Qris not found", err, http.StatusNotFound)
		} else {
			h.logAndRespondError(c, "Failed to get qris", err, http.StatusInternalServerError)
		}
		return
	}

	response := qris.QrisGetByIPResponse{
		Message: "qris details retrieved successfully",
		Data:    items,
	}

	c.JSON(http.StatusOK, response)
}

// GetQrisStats godoc
// @Summary Get qris statistics
// @Description Returns comprehensive statistics about qris data
// @Tags Qris
// @Accept json
// @Produce json
// @Param status query string false "Filter statistics by status"
// @Success 200 {object} models.AggregateData "Statistics data"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /qris/stats [get]
func (h *QrisHandler) GetQrisStats(c *gin.Context) {
	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
	defer cancel()

	filter := h.parseFilterParams(c)
	aggregateData, err := h.getAggregateData(ctx, dbConn, filter)
	if err != nil {
		h.logAndRespondError(c, "Failed to get statistics", err, http.StatusInternalServerError)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message": "Statistik qris berhasil diambil",
		"data":    aggregateData,
	})
}

// Database operations
func (h *QrisHandler) getQrisByID(ctx context.Context, dbConn *sql.DB, id int) (*qris.Qris, error) {
	query := "SELECT id, status, created_at, updated_at, display_name, display_amount, qrvalue, ip, display_nobill, posdevice FROM t_qrdata WHERE id = $1 AND status = '1'"
	row := dbConn.QueryRowContext(ctx, query, id)

	var item qris.Qris
	err := row.Scan(&item.ID, &item.Status, &item.CreatedAt, &item.UpdatedAt, &item.DisplayName, &item.DisplayAmount, &item.QrValue, &item.IPAddress, &item.DisplayNoBill, &item.PosDevice)
	if err != nil {
		return nil, err
	}

	return &item, nil
}

func (h *QrisHandler) getQrisByIP(ctx context.Context, dbConn *sql.DB, ip string, c *gin.Context) ([]qris.Qris, error) {
	// Use QrisFilter to filter by IP
	filter := qris.QrisFilter{
		IPAddress: &ip,
	}

	// Parse pagination parameters from query, default to 10, 0
	limit, offset, err := h.parsePaginationParams(c)
	if err != nil {
		return nil, err
	}

	// Use fetchQris to get all rows matching the IP
	items, err := h.fetchQris(ctx, dbConn, filter, limit, offset)
	if err != nil {
		return nil, err
	}
	return items, nil
}

/*func (h *QrisHandler) createQris(ctx context.Context, dbConn *sql.DB, req *qris.QrisCreateRequest) (*qris.Qris, error) {
	id := uuid.New().String()
	now := time.Now()

	query := "INSERT INTO data_qris_qris (id, status, date_created, date_updated, name) VALUES ($1, $2, $3, $4, $5) RETURNING id, status, sort, user_created, date_created, user_updated, date_updated, name"
	row := dbConn.QueryRowContext(ctx, query, id, req.Status, now, now, req.Name)

	var item qris.Qris
	err := row.Scan(&item.ID, &item.Status, &item.Sort, &item.UserCreated, &item.DateCreated, &item.UserUpdated, &item.DateUpdated, &item.Name)
	if err != nil {
		return nil, fmt.Errorf("failed to create qris: %w", err)
	}

	return &item, nil
}*/

/*func (h *QrisHandler) updateQris(ctx context.Context, dbConn *sql.DB, req *qris.QrisUpdateRequest) (*qris.Qris, error) {
	now := time.Now()

	query := "UPDATE data_qris_qris SET status = $2, date_updated = $3, name = $4 WHERE id = $1 AND status != 'deleted' RETURNING id, status, sort, user_created, date_created, user_updated, date_updated, name"
	row := dbConn.QueryRowContext(ctx, query, req.ID, req.Status, now, req.Name)

	var item qris.Qris
	err := row.Scan(&item.ID, &item.Status, &item.Sort, &item.UserCreated, &item.DateCreated, &item.UserUpdated, &item.DateUpdated, &item.Name)
	if err != nil {
		return nil, fmt.Errorf("failed to update qris: %w", err)
	}

	return &item, nil
}*/

/*func (h *QrisHandler) deleteQris(ctx context.Context, dbConn *sql.DB, id string) error {
	now := time.Now()
	query := "UPDATE data_qris_qris SET status = 'deleted', updated_at = $2 WHERE id = $1 AND status != 'deleted'"

	result, err := dbConn.ExecContext(ctx, query, id, now)
	if err != nil {
		return fmt.Errorf("failed to delete qris: %w", err)
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("failed to get affected rows: %w", err)
	}

	if rowsAffected == 0 {
		return sql.ErrNoRows
	}

	return nil
}*/

func (h *QrisHandler) fetchQris(ctx context.Context, dbConn *sql.DB, filter qris.QrisFilter, limit, offset int) ([]qris.Qris, error) {
	whereClause, args := h.buildWhereClause(filter)
	query := fmt.Sprintf("SELECT id, posdevice, ip, invoice_number, qrvalue, status, created_at, updated_at, display_nobill, display_name, display_amount FROM t_qrdata WHERE %s ORDER BY created_at DESC NULLS LAST LIMIT $%d OFFSET $%d", whereClause, len(args)+1, len(args)+2)
	args = append(args, limit, offset)

	// Log the query and arguments
	log.Printf("[DEBUG] SQL Query: %s", query)
	log.Printf("[DEBUG] SQL Args: %#v", args)

	rows, err := dbConn.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, fmt.Errorf("fetch qris query failed: %w", err)
	}
	defer rows.Close()

	items := make([]qris.Qris, 0, limit)
	for rows.Next() {
		item, err := h.scanQris(rows)
		if err != nil {
			return nil, fmt.Errorf("scan Qris failed: %w", err)
		}
		items = append(items, item)
	}

	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("rows iteration error: %w", err)
	}

	log.Printf("Successfully fetched %d qris with filters applied", len(items))
	return items, nil
}

// Optimized scanning function
func (h *QrisHandler) scanQris(rows *sql.Rows) (qris.Qris, error) {
	var item qris.Qris

	// Scan into individual fields to handle nullable types properly
	err := rows.Scan(
		&item.ID,
		&item.PosDevice,
		&item.IPAddress,
		&item.InvoiceNumber,
		&item.QrValue,
		&item.Status,
		&item.CreatedAt,
		&item.UpdatedAt,
		&item.DisplayNoBill,
		&item.DisplayName,
		&item.DisplayAmount,
	)

	return item, err
}

func (h *QrisHandler) getTotalCount(ctx context.Context, dbConn *sql.DB, filter qris.QrisFilter, total *int) error {
	whereClause, args := h.buildWhereClause(filter)
	countQuery := fmt.Sprintf("SELECT COUNT(*) FROM t_qrdata WHERE %s", whereClause)

	// Log the query and arguments
	log.Printf("[DEBUG] SQL Count Query: %s", countQuery)
	log.Printf("[DEBUG] SQL Count Args: %#v", args)

	if err := dbConn.QueryRowContext(ctx, countQuery, args...).Scan(total); err != nil {
		return fmt.Errorf("total count query failed: %w", err)

	}
	return nil
}

// Get comprehensive aggregate data dengan filter support
func (h *QrisHandler) getAggregateData(ctx context.Context, dbConn *sql.DB, filter qris.QrisFilter) (*models.AggregateData, error) {
	aggregate := &models.AggregateData{
		ByStatus: make(map[string]int),
	}

	// Build where clause untuk filter
	whereClause, args := h.buildWhereClause(filter)

	// Use concurrent execution untuk performance
	var wg sync.WaitGroup
	var mu sync.Mutex
	errChan := make(chan error, 4)

	// 1. Count by status
	wg.Add(1)
	go func() {
		defer wg.Done()
		statusQuery := fmt.Sprintf("SELECT status, COUNT(*) FROM t_qrdata WHERE %s GROUP BY status ORDER BY status", whereClause)

		rows, err := dbConn.QueryContext(ctx, statusQuery, args...)
		if err != nil {
			errChan <- fmt.Errorf("status query failed: %w", err)
			return
		}
		defer rows.Close()

		mu.Lock()
		for rows.Next() {
			var status string
			var count int
			if err := rows.Scan(&status, &count); err != nil {
				mu.Unlock()
				errChan <- fmt.Errorf("status scan failed: %w", err)
				return
			}
			aggregate.ByStatus[status] = count
			switch status {
			case "active":
				aggregate.TotalActive = count
			case "draft":
				aggregate.TotalDraft = count
			case "inactive":
				aggregate.TotalInactive = count
			}
		}
		mu.Unlock()

		if err := rows.Err(); err != nil {
			errChan <- fmt.Errorf("status iteration error: %w", err)
		}
	}()

	// 2. Get last updated time dan today statistics
	wg.Add(1)
	go func() {
		defer wg.Done()

		// Last updated
		lastUpdatedQuery := fmt.Sprintf("SELECT MAX(updated_at) FROM t_qrdata WHERE %s AND updated_at IS NOT NULL", whereClause)
		var lastUpdated sql.NullTime
		if err := dbConn.QueryRowContext(ctx, lastUpdatedQuery, args...).Scan(&lastUpdated); err != nil {
			errChan <- fmt.Errorf("last updated query failed: %w", err)
			return
		}

		// Today statistics
		today := time.Now().Format("2006-01-02")
		todayStatsQuery := fmt.Sprintf(`
			SELECT 
				SUM(CASE WHEN DATE(created_at) = $%d THEN 1 ELSE 0 END) as created_today,
				SUM(CASE WHEN DATE(updated_at) = $%d AND DATE(created_at) != $%d THEN 1 ELSE 0 END) as updated_today
			FROM t_qrdata 
			WHERE %s`, len(args)+1, len(args)+1, len(args)+1, whereClause)

		todayArgs := append(args, today)
		var createdToday, updatedToday int
		if err := dbConn.QueryRowContext(ctx, todayStatsQuery, todayArgs...).Scan(&createdToday, &updatedToday); err != nil {
			errChan <- fmt.Errorf("today stats query failed: %w", err)
			return
		}

		mu.Lock()
		if lastUpdated.Valid {
			aggregate.LastUpdated = &lastUpdated.Time
		}
		aggregate.CreatedToday = createdToday
		aggregate.UpdatedToday = updatedToday
		mu.Unlock()
	}()

	// Wait for all goroutines
	wg.Wait()
	close(errChan)

	// Check for errors
	for err := range errChan {
		if err != nil {
			return nil, err
		}
	}

	return aggregate, nil
}

// Enhanced error handling
func (h *QrisHandler) logAndRespondError(c *gin.Context, message string, err error, statusCode int) {
	log.Printf("[ERROR] %s: %v", message, err)
	h.respondError(c, message, err, statusCode)
}

func (h *QrisHandler) respondError(c *gin.Context, message string, err error, statusCode int) {
	errorMessage := message
	if gin.Mode() == gin.ReleaseMode {
		errorMessage = "Internal server error"
	}

	c.JSON(statusCode, models.ErrorResponse{
		Error:     errorMessage,
		Code:      statusCode,
		Message:   err.Error(),
		Timestamp: time.Now(),
	})
}

// Parse pagination parameters dengan validation yang lebih ketat
func (h *QrisHandler) parsePaginationParams(c *gin.Context) (int, int, error) {
	limit := 10 // Default limit
	offset := 0 // Default offset

	if limitStr := c.Query("limit"); limitStr != "" {
		parsedLimit, err := strconv.Atoi(limitStr)
		if err != nil {
			return 0, 0, fmt.Errorf("invalid limit parameter: %s", limitStr)
		}
		if parsedLimit <= 0 {
			return 0, 0, fmt.Errorf("limit must be greater than 0")
		}
		if parsedLimit > 100 {
			return 0, 0, fmt.Errorf("limit cannot exceed 100")
		}
		limit = parsedLimit
	}

	if offsetStr := c.Query("offset"); offsetStr != "" {
		parsedOffset, err := strconv.Atoi(offsetStr)
		if err != nil {
			return 0, 0, fmt.Errorf("invalid offset parameter: %s", offsetStr)
		}
		if parsedOffset < 0 {
			return 0, 0, fmt.Errorf("offset cannot be negative")
		}
		offset = parsedOffset
	}

	log.Printf("Pagination - Limit: %d, Offset: %d", limit, offset)
	return limit, offset, nil
}

func (h *QrisHandler) parseFilterParams(c *gin.Context) qris.QrisFilter {
	filter := qris.QrisFilter{}

	if status := c.Query("status"); status != "" {
		if models.IsValidStatus(status) {
			filter.Status = &status
		}
	}

	if ip := c.Query("ip"); ip != "" {
		filter.IPAddress = &ip
	}

	if display_name := c.Query("display_name"); display_name != "" {
		filter.DisplayName = &display_name
	}

	if posdevice := c.Query("posdevice"); posdevice != "" {
		filter.PosDevice = &posdevice
	}

	if search := c.Query("search"); search != "" {
		filter.Search = &search
	}

	// Parse date filters
	if dateFromStr := c.Query("date_from"); dateFromStr != "" {
		if dateFrom, err := time.Parse("2006-01-02", dateFromStr); err == nil {
			filter.DateFrom = &dateFrom
		}
	}

	if dateToStr := c.Query("date_to"); dateToStr != "" {
		if dateTo, err := time.Parse("2006-01-02", dateToStr); err == nil {
			filter.DateTo = &dateTo
		}
	}

	return filter
}

// Build WHERE clause dengan filter parameters
func (h *QrisHandler) buildWhereClause(filter qris.QrisFilter) (string, []interface{}) {
	conditions := []string{"status = '1'"}
	args := []interface{}{}
	paramCount := 1

	if filter.Status != nil {
		conditions = append(conditions, fmt.Sprintf("status = $%d", paramCount))
		args = append(args, *filter.Status)
		paramCount++
	}

	if filter.IPAddress != nil {
		conditions = append(conditions, fmt.Sprintf(`"ip" ILIKE $%d`, paramCount))
		args = append(args, "%"+*filter.IPAddress+"%")
		paramCount++
	}

	if filter.DisplayName != nil {
		conditions = append(conditions, fmt.Sprintf(`"display_name" ILIKE $%d`, paramCount))
		args = append(args, "%"+*filter.DisplayName+"%")
		paramCount++
	}

	if filter.PosDevice != nil {
		conditions = append(conditions, fmt.Sprintf(`"posdevice" ILIKE $%d`, paramCount))
		args = append(args, "%"+*filter.PosDevice+"%")
		paramCount++
	}

	if filter.Search != nil {
		searchCondition := fmt.Sprintf(`(
            "ip" ILIKE $%d OR 
            "display_name" ILIKE $%d OR 
            "posdevice" ILIKE $%d
        )`, paramCount, paramCount, paramCount)
		conditions = append(conditions, searchCondition)
		searchTerm := "%" + *filter.Search + "%"
		args = append(args, searchTerm)
		paramCount++
	}

	/*if filter.Search != nil {
		searchTerm := "%" + *filter.Search + "%"
		searchFields := []string{"ip", "display_name", "posdevice"}
		searchConditions := make([]string, 0, len(searchFields))
		for _, field := range searchFields {
			searchConditions = append(searchConditions, fmt.Sprintf("%s ILIKE $%d", field, paramCount))
			args = append(args, searchTerm)
			paramCount++
		}
		// Combine with OR
		conditions = append(conditions, fmt.Sprintf("(%s)", strings.Join(searchConditions, " OR ")))
	}*/

	if filter.DateFrom != nil {
		conditions = append(conditions, fmt.Sprintf("created_at >= $%d", paramCount))
		args = append(args, *filter.DateFrom)
		paramCount++
	}

	if filter.DateTo != nil {
		conditions = append(conditions, fmt.Sprintf("created_at <= $%d", paramCount))
		args = append(args, filter.DateTo.Add(24*time.Hour-time.Nanosecond))
		paramCount++
	}

	return strings.Join(conditions, " AND "), args
}

func (h *QrisHandler) calculateMeta(limit, offset, total int) models.MetaResponse {
	totalPages := 0
	currentPage := 1
	if limit > 0 {
		totalPages = (total + limit - 1) / limit // Ceiling division
		currentPage = (offset / limit) + 1
	}

	return models.MetaResponse{
		Limit:       limit,
		Offset:      offset,
		Total:       total,
		TotalPages:  totalPages,
		CurrentPage: currentPage,
		HasNext:     offset+limit < total,
		HasPrev:     offset > 0,
	}
}

// validateQrisSubmission performs validation for duplicate entries and daily submission limits
/*func (h *QrisHandler) validateQrisSubmission(ctx context.Context, dbConn *sql.DB, req *qris.QrisCreateRequest) error {
	// Import the validation utility
	validator := validation.NewDuplicateValidator(dbConn)

	// Use default configuration
	config := validation.ValidationConfig{
		TableName:      "data_qris_qris",
		IDColumn:       "id",
		StatusColumn:   "status",
		DateColumn:     "date_created",
		ActiveStatuses: []string{"active", "draft"},
	}

	// Validate duplicate entries with active status for today
	err := validator.ValidateDuplicate(ctx, config, "dummy_id")
	if err != nil {
		return fmt.Errorf("validation failed: %w", err)
	}

	// Validate once per day submission
	err = validator.ValidateOncePerDay(ctx, "data_qris_qris", "id", "date_created", "daily_limit")
	if err != nil {
		return fmt.Errorf("daily submission limit exceeded: %w", err)
	}

	return nil
}*/

// Example usage of the validation utility with custom configuration
/*func (h *QrisHandler) validateWithCustomConfig(ctx context.Context, dbConn *sql.DB, req *qris.QrisCreateRequest) error {
	// Create validator instance
	validator := validation.NewDuplicateValidator(dbConn)

	// Use custom configuration
	config := validation.ValidationConfig{
		TableName:      "data_qris_qris",
		IDColumn:       "id",
		StatusColumn:   "status",
		DateColumn:     "date_created",
		ActiveStatuses: []string{"active", "draft"},
		AdditionalFields: map[string]interface{}{
			"name": req.Name,
		},
	}

	// Validate with custom fields
	fields := map[string]interface{}{
		"name": *req.Name,
	}

	err := validator.ValidateDuplicateWithCustomFields(ctx, config, fields)
	if err != nil {
		return fmt.Errorf("custom validation failed: %w", err)
	}

	return nil
}*/

// GetLastSubmissionTime example
/*func (h *QrisHandler) getLastSubmissionTimeExample(ctx context.Context, dbConn *sql.DB, identifier string) (*time.Time, error) {
	validator := validation.NewDuplicateValidator(dbConn)
	return validator.GetLastSubmissionTime(ctx, "t_qrdata", "id", "created_at", identifier)
}*/

// fetchDynamic executes dynamic query
func (h *QrisHandler) fetchDynamic(ctx context.Context, dbConn *sql.DB, query utils.DynamicQuery) ([]qris.Qris, int, error) {
	// Setup query builder
	countBuilder := utils.NewQueryBuilder("t_qrdata").
		SetColumnMapping(map[string]string{
			"id":             "id",
			"posdevice":      "posdevice",
			"ip":             "ip",
			"invoice_number": "invoice_number",
			"qrvalue":        "qrvalue",
			"status":         "status",
			"created_at":     "created_at",
			"updated_at":     "updated_at",
			"display_nobill": "display_nobill",
			"display_name":   "display_name",
			"display_amount": "display_amount",
		}).
		SetAllowedColumns([]string{
			"id",
			"posdevice",
			"ip",
			"invoice_number",
			"qrvalue",
			"status",
			"created_at",
			"updated_at",
			"display_nobill",
			"display_name",
			"display_amount",
		})

	mainBuilder := utils.NewQueryBuilder("t_qrdata").
		SetColumnMapping(map[string]string{
			"id":             "id",
			"posdevice":      "posdevice",
			"ip":             "ip",
			"invoice_number": "invoice_number",
			"qrvalue":        "qrvalue",
			"status":         "status",
			"created_at":     "created_at",
			"updated_at":     "updated_at",
			"display_nobill": "display_nobill",
			"display_name":   "display_name",
			"display_amount": "display_amount",
		}).
		SetAllowedColumns([]string{
			"id",
			"posdevice",
			"ip",
			"invoice_number",
			"qrvalue",
			"status",
			"created_at",
			"updated_at",
			"display_nobill",
			"display_name",
			"display_amount",
		})

	// Add default filter to exclude deleted records
	if len(query.Filters) > 0 {
		query.Filters = append([]utils.FilterGroup{{
			Filters: []utils.DynamicFilter{{
				Column:   "status",
				Operator: utils.OpEqual,
				Value:    "1",
			}},
			LogicOp: "AND",
		}}, query.Filters...)
	} else {
		query.Filters = []utils.FilterGroup{{
			Filters: []utils.DynamicFilter{{
				Column:   "status",
				Operator: utils.OpEqual,
				Value:    "1",
			}},
			LogicOp: "AND",
		}}
	}

	// Execute queries sequentially to avoid race conditions
	var total int
	var items []qris.Qris

	// 1. Get total count first
	countQuery := query
	countQuery.Limit = 0
	countQuery.Offset = 0

	countSQL, countArgs, err := countBuilder.BuildCountQuery(countQuery)
	if err != nil {
		return nil, 0, fmt.Errorf("failed to build count query: %w", err)
	}

	if err := dbConn.QueryRowContext(ctx, countSQL, countArgs...).Scan(&total); err != nil {
		return nil, 0, fmt.Errorf("failed to get total count: %w", err)
	}

	// 2. Get main data
	mainSQL, mainArgs, err := mainBuilder.BuildQuery(query)

	// Inside goroutines, before executing queries:
	log.Printf("[DEBUG] Dynamic SQL Query: %s", mainSQL)
	log.Printf("[DEBUG] Dynamic SQL Args: %#v", mainArgs)

	if err != nil {
		return nil, 0, fmt.Errorf("failed to build main query: %w", err)
	}

	rows, err := dbConn.QueryContext(ctx, mainSQL, mainArgs...)
	if err != nil {
		return nil, 0, fmt.Errorf("failed to execute main query: %w", err)
	}
	defer rows.Close()

	for rows.Next() {
		item, err := h.scanQris(rows)
		if err != nil {
			return nil, 0, fmt.Errorf("failed to scan qris: %w", err)
		}
		items = append(items, item)
	}

	if err := rows.Err(); err != nil {
		return nil, 0, fmt.Errorf("rows iteration error: %w", err)
	}

	return items, total, nil
}

// GetSearchDynamic godoc
// @Summary Get search with dynamic filtering
// @Description Returns search with advanced dynamic filtering like Directus
// @Tags Search
// @Accept json
// @Produce json
// @Param fields query string false "Fields to select (e.g., fields=*.*)"
// @Param filter[column][operator] query string false "Dynamic filters (e.g., filter[name][_eq]=value)"
// @Param sort query string false "Sort fields (e.g., sort=date_created,-name)"
// @Param limit query int false "Limit" default(10)
// @Param offset query int false "Offset" default(0)
// @Success 200 {object} qris.QrisGetResponse "Success response"
// @Failure 400 {object} models.ErrorResponse "Bad request"
// @Failure 500 {object} models.ErrorResponse "Internal server error"
// @Router /qris/dynamic [get]
func (h *QrisHandler) GetSearchDynamic(c *gin.Context) {
	// Parse query parameters
	parser := utils.NewQueryParser().SetLimits(10, 100)
	dynamicQuery, err := parser.ParseQuery(c.Request.URL.Query())
	if err != nil {
		h.respondError(c, "Invalid query parameters", err, http.StatusBadRequest)
		return
	}

	log.Printf("[DEBUG] DynamicQuery.Filters: %#v", dynamicQuery.Filters)

	// Get database connection
	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	// Create context with timeout
	ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
	defer cancel()

	// Execute query with dynamic filtering
	items, total, err := h.fetchDynamic(ctx, dbConn, dynamicQuery)
	if err != nil {
		h.logAndRespondError(c, "Failed to fetch data", err, http.StatusInternalServerError)
		return
	}

	// Build response
	meta := h.calculateMeta(dynamicQuery.Limit, dynamicQuery.Offset, total)
	response := qris.QrisGetResponse{
		Message: "Data qris berhasil diambil",
		Data:    items,
		Meta:    meta,
	}

	c.JSON(http.StatusOK, response)
}

// SearchAdvanced provides advanced search capabilities
func (h *QrisHandler) SearchAdvanced(c *gin.Context) {
	// Parse complex search parameters
	searchQuery := c.Query("q")
	if searchQuery == "" {
		// If no search query provided, return all records with default sorting
		query := utils.DynamicQuery{
			Fields:  []string{"*"},
			Filters: []utils.FilterGroup{}, // Empty filters - fetchDynamic will add default deleted filter
			Sort: []utils.SortField{{
				Column: "created_at",
				Order:  "DESC",
			}},
			Limit:  20,
			Offset: 0,
		}

		// Parse pagination if provided
		if limit := c.Query("limit"); limit != "" {
			if l, err := strconv.Atoi(limit); err == nil && l > 0 && l <= 100 {
				query.Limit = l
			}
		}

		if offset := c.Query("offset"); offset != "" {
			if o, err := strconv.Atoi(offset); err == nil && o >= 0 {
				query.Offset = o
			}
		}

		// Get database connection
		dbConn, err := h.db.GetDB("postgres_satudata")
		if err != nil {
			h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
			return
		}

		ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
		defer cancel()

		// Execute query to get all records
		items, total, err := h.fetchDynamic(ctx, dbConn, query)
		if err != nil {
			h.logAndRespondError(c, "Failed to fetch data", err, http.StatusInternalServerError)
			return
		}

		// Build response
		meta := h.calculateMeta(query.Limit, query.Offset, total)
		response := qris.QrisGetResponse{
			Message: "All records retrieved (no search query provided)",
			Data:    items,
			Meta:    meta,
		}

		c.JSON(http.StatusOK, response)
		return
	}

	// Build dynamic query for search
	query := utils.DynamicQuery{
		Fields: []string{"*"},
		Filters: []utils.FilterGroup{{
			Filters: []utils.DynamicFilter{
				{
					Column:   "status",
					Operator: utils.OpEqual,
					Value:    "1",
				},
				{
					Column:   "ip",
					Operator: utils.OpContains,
					Value:    searchQuery,
					LogicOp:  "OR",
				},
				{
					Column:   "display_name",
					Operator: utils.OpContains,
					Value:    searchQuery,
					LogicOp:  "OR",
				},
				{
					Column:   "posdevice",
					Operator: utils.OpContains,
					Value:    searchQuery,
					LogicOp:  "OR",
				},
			},
			LogicOp: "AND",
		}},
		Sort: []utils.SortField{{
			Column: "created_at",
			Order:  "DESC",
		}},
		Limit:  20,
		Offset: 0,
	}

	// Parse pagination if provided
	if limit := c.Query("limit"); limit != "" {
		if l, err := strconv.Atoi(limit); err == nil && l > 0 && l <= 100 {
			query.Limit = l
		}
	}
	if offset := c.Query("offset"); offset != "" {
		if o, err := strconv.Atoi(offset); err == nil && o >= 0 {
			query.Offset = o
		}
	}

	// Get database connection
	dbConn, err := h.db.GetDB("simrs_backup")
	if err != nil {
		h.logAndRespondError(c, "Database connection failed", err, http.StatusInternalServerError)
		return
	}

	ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
	defer cancel()

	// Execute search
	items, total, err := h.fetchDynamic(ctx, dbConn, query)
	if err != nil {
		h.logAndRespondError(c, "Search failed", err, http.StatusInternalServerError)
		return
	}

	// Build response
	meta := h.calculateMeta(query.Limit, query.Offset, total)
	response := qris.QrisGetResponse{
		Message: fmt.Sprintf("Search results for '%s'", searchQuery),
		Data:    items,
		Meta:    meta,
	}

	c.JSON(http.StatusOK, response)
}
