package queries

import (
	"database/sql"
	"fmt"
	"strings"
	"time"
)

func BulkUpdateOrderLineDueDate(mssql *sql.DB, orderHeaderID string, dueDate string, username string) (int64, bool, error) {
	orderID := strings.TrimSpace(orderHeaderID)
	dateText := strings.TrimSpace(dueDate)
	user := strings.TrimSpace(username)

	if orderID == "" {
		return 0, false, fmt.Errorf("orderHeaderID zorunlu")
	}
	if dateText == "" {
		return 0, false, fmt.Errorf("dueDate zorunlu")
	}
	if _, err := time.Parse("2006-01-02", dateText); err != nil {
		return 0, false, fmt.Errorf("gecersiz tarih: %w", err)
	}
	if user == "" {
		user = "system"
	}

	tx, err := mssql.Begin()
	if err != nil {
		return 0, false, err
	}
	defer tx.Rollback()

	lineRes, err := tx.Exec(`
UPDATE BAGGI_V3.dbo.trOrderLine
SET
	DeliveryDate = CAST(@p1 AS DATETIME),
	PlannedDateOfLading = CAST(@p1 AS DATETIME),
	LastUpdatedUserName = @p2,
	LastUpdatedDate = GETDATE()
WHERE OrderHeaderID = @p3
  AND ISNULL(IsClosed, 0) = 0
`, dateText, user, orderID)
	if err != nil {
		return 0, false, err
	}

	lineCount, err := lineRes.RowsAffected()
	if err != nil {
		return 0, false, err
	}

	headerRes, err := tx.Exec(`
UPDATE BAGGI_V3.dbo.trOrderHeader
SET
	AverageDueDate = CAST(@p1 AS DATETIME),
	LastUpdatedUserName = @p2,
	LastUpdatedDate = GETDATE()
WHERE OrderHeaderID = @p3
`, dateText, user, orderID)
	if err != nil {
		return 0, false, err
	}

	headerCount, err := headerRes.RowsAffected()
	if err != nil {
		return 0, false, err
	}

	if err := tx.Commit(); err != nil {
		return 0, false, err
	}

	return lineCount, headerCount > 0, nil
}
