package utils

const PAGE_SIZE = 10

const PAGE_SIZE_STRING = "10"

// order page filters
const FUTURE_FILTER = 1
const PAST_FILTER = 2
const FILLED_FILTER = 4
const UNFILLED_FILTER = 8
const DELIVERED_FILTER = 16
const UNDELIVERED_FILTER = 32
const PAID_FILTER = 64
const UNPAID_FILTER = 128
const ASCEND_DATE_DUE = 256

func GetOrderTableQueryString(filter int64) string {
	query_string_first_part := `
	WITH order_bill AS (
	SELECT
		orec.id,
		COALESCE(order_total, 0) AS order_total,
		COALESCE(order_total - orec.amount_paid, 0) AS balance
	FROM
		order_record orec
		INNER JOIN (
			SELECT 
				orec.id,
				SUM(quantity * price) AS order_total
			FROM
				order_record orec
				LEFT JOIN order_item oi ON oi.order_id = orec.id
				LEFT JOIN item i ON oi.item_id = i.id
				LEFT JOIN item_price_history iph ON iph.item_id = i.id
					AND iph.valid_from <= oi.created_at
					AND (iph.valid_to IS NULL OR iph.valid_to > oi.created_at)
			GROUP BY orec.id
		) totals ON orec.id = totals.id
	)
	
	SELECT
		orec.id,
		user_id,
		orderer,
		date_due,
		date_placed,
		amount_paid,
		order_total,
		balance,
		filled,
		delivered
	FROM
		order_record orec
		INNER JOIN order_bill ON order_bill.id = orec.id
	`

	order := "DESC"
	if filter&ASCEND_DATE_DUE > 0 {
		order = "ASC"
	}

	query_string_second_part := `
		ORDER BY date_due ` + order + ` 
		OFFSET $1
		LIMIT $2;
	`
	filter = filter & ^ASCEND_DATE_DUE

	conditions := `
	WHERE
		orderer LIKE '%' || $3 || '%'
		AND TO_CHAR(date_due, 'YYYY-MM-DD') LIKE '%' || $4 || '%'
		AND TO_CHAR(date_placed, 'YYYY-MM-DD') LIKE '%' || $5 || '%'
	`
	if filter > 0 {
		if filter&FUTURE_FILTER > 0 {
			conditions += "AND date_due > now()\n"
		}
		if filter&PAST_FILTER > 0 {
			conditions += "AND date_due < now()\n"
		}
		if filter&FILLED_FILTER > 0 {
			conditions += "AND filled = TRUE\n"
		}
		if filter&UNFILLED_FILTER > 0 {
			conditions += "AND filled = FALSE\n"
		}
		if filter&DELIVERED_FILTER > 0 {
			conditions += "AND delivered = TRUE\n"
		}
		if filter&UNDELIVERED_FILTER > 0 {
			conditions += "AND delivered = FALSE\n"
		}
		if filter&PAID_FILTER > 0 {
			conditions += "AND paid = TRUE\n"
		}
		if filter&UNPAID_FILTER > 0 {
			conditions += "AND paid = FALSE\n"
		}
	}

	query_string := query_string_first_part + conditions + query_string_second_part

	return query_string
}
