DROP TABLE pricing.target_prices;

CREATE TABLE pricing.target_prices (
	stlc        nvarchar(8)     NOT NULL,
	ds          nvarchar(20)    NOT NULL,
	chan        nvarchar(3)     NOT NULL,
	tier        nvarchar(1)     NOT NULL,
	vol         nvarchar(20)    NOT NULL,
	lower_bound int             NOT NULL,
	upper_bound int                 NULL,
	price       numeric(28,6)   NOT NULL,
	math        nvarchar(MAX)       NULL
);

ALTER TABLE pricing.target_prices
ADD CONSTRAINT uq_target_prices_unique_combo
UNIQUE (stlc, ds, chan, tier, vol, lower_bound);

DELETE FROM pricing.target_prices;

INSERT INTO 
	pricing.target_prices
SELECT
	stlc,
	ds,
	chan,
	tier,
	vol,
	-- Extract lower bound: text between '[' and ','
	TRY_CAST(SUBSTRING(vol, 2, CHARINDEX(',', vol) - 2) AS INT) AS lower_bound,
	-- Extract upper bound: text between ',' and ')'
	CASE
		WHEN RIGHT(vol, 2) = ',)' THEN NULL
		ELSE TRY_CAST(SUBSTRING(vol, CHARINDEX(',', vol) + 1, LEN(vol) - CHARINDEX(',', vol) - 1) AS INT)
	END AS upper_bound,
	price,
	math
FROM
	usmidsap02.ubm.pricequote.target_prices_view;

--SELECT COUNT(*) FROM pricing.target_prices
