package queries

const CREATE_ITEM = `
INSERT INTO item(item_name, in_season) VALUES ($1, $2);
`

const CREATE_ITEM_PRICE = `
INSERT INTO item_price_history(item_id, price) VALUES ($1, $2);
`

const SET_ITEM_PRICE_VALID_TO_DATE = `
UPDATE item_price_history SET valid_to = now() 
WHERE item_id IN (
	SELECT item_id FROM item_price_history WHERE item_id = $1 ORDER BY valid_from DESC LIMIT 1
)
`

const GET_CURRENT_ITEM_PRICE = `
SELECT
	i.id,
	i.item_name,
	iph.price AS unit_price,
	i.in_season
	FROM item i
	INNER JOIN item_price_history iph ON iph.item_id = i.id
		AND i.id = $1
	ORDER BY iph.valid_from DESC
	LIMIT 1;
`

const GET_CURRENT_ITEMS_PRICE = `
WITH latest_price_identifiers AS (
	SELECT
		i.id,
		i.item_name,
		MAX(iph.valid_from) AS valid_from
		FROM item i
		INNER JOIN item_price_history iph ON iph.item_id = i.id
		GROUP BY (i.id, i.item_name)
)

SELECT
	lpi.id,
	lpi.item_name,
	iph.price,
	i.in_season
FROM
	latest_price_identifiers lpi
	INNER JOIN item_price_history iph
		ON lpi.id = iph.item_id
			AND lpi.valid_from = iph.valid_from
	INNER JOIN item i
		ON iph.item_id = i.id;`
const GET_ORDER_ITEM_PRICE = `
SELECT
	oi.item_id,
	oi.order_id,
	i.item_name,
	oi.quantity,
	oi.made,
	oi.created_at,
	oi.quantity * iph.price AS total_price,
	iph.price AS unit_price
FROM
	order_item oi
	INNER JOIN item i ON oi.item_id = i.id
		AND oi.item_id = $1
		AND oi.order_id = $2
	INNER 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);
`

const ADD_ITEM_TO_ORDER = `
INSERT INTO order_item (item_id, order_id, quantity, created_at) VALUES ($1, $2, $3, $4) ON CONFLICT (item_id, order_id) DO UPDATE SET
	quantity = $3,
	created_at = $4`

const SET_QUANTITY = `
UPDATE order_item SET quantity = $1 WHERE item_id = $2 AND order_id = $3;
`

const SET_MADE = `
UPDATE order_item SET made = $1 WHERE item_id = $2 AND order_id = $3;
`

const GET_ORDER_ITEMS = `
SELECT
	oi.item_id,
	oi.order_id,
	i.item_name,
	oi.quantity,
	oi.made,
	oi.created_at,
	oi.quantity * iph.price AS total_price,
	iph.price AS unit_price
FROM
	order_item oi
	INNER JOIN item i ON oi.item_id = i.id
		AND oi.order_id = $1
	INNER 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);
`

const REMOVE_ITEM_FROM_ORDER = `
DELETE FROM order_item WHERE item_id = $1 AND order_id = $2;
`

const SET_ITEM_IS_IN_SEASON = `
UPDATE item SET in_season = $1 WHERE id = $2;
`

const GET_ORDER_MADE_DETAILS = `
SELECT
	id,
	filled
FROM
	order_record
WHERE
	id = $1;
`

const GET_ITEM_PRICE_HISTORY = `
SELECT
	i.id,
	i.item_name,
	iph.price,
	iph.valid_from,
	COALESCE(iph.valid_to, now()) as valid_to
FROM
	item i
	INNER JOIN item_price_history iph
	ON i.id = iph.item_id
		AND i.id = $1;
`
