Object.entries(require('./common.js')).forEach(([name, exported]) => global[name] = exported);
let m = new Map();
function persist(s, p, q) {
	s = s.replace(/\(|\)|\s/g, '');
	if(s.length < 14) {
		s = s.padStart(14, '0');
	} else if(s.length > 14) {
		s = s.substring(2, 16);
	}
/*
00000030087859 OCB ROLLING PAPERS
00000042230731 Gizeh Rolling Papers
00011711334506 Grav 6\" Upright Bubbler
00011711336807 Grav 6\" Sherlock Hand Pipe
00070330600171 Lighter
00077170109963 OCB 79/70 Hand Roller

04250153072270 3-Piece Acrylic Grinder
04897083010011 Green Jay Single Carrier
04897083010127 Green Jay E Lighter
06971154220221 Yocan Evolve 3-in-1 Vaporizer Kit
06972136450100 Herbva 5G Vaporizer

don't give a fuck about these products, so this conditional is safe
*/
	if(/00[1-9]\d{11}/.test(s)) {
		if(m.has(s)) {
			let old = m.get(s);
			if(q > old[1] || ((q === 0 && old[1] === 0 || q > 0 && old[1] > 0) && p > old[0])) {
				m.set(s, [(p + '').slice(0, -2) + '.' + (p + '').slice(-2), q]);
			}
		} else {
			m.set(s, [(p + '').slice(0, -2) + '.' + (p + '').slice(-2), q]);
		}
	}
}
let products = request({
	url: 'https://api.getgreenline.co/api/v1/external/company/847/location/848/posListings',
	headers: {'api-key': process.env.GREENLINE_API_KEY, 'external-api-auth-token': process.env.SUMMIT_API_AUTH_TOKEN}
}).then(x => JSON.parse(x).products);
let storeID = postgres.connect()
	.then(() => postgres.query('begin'))
	.then(async () => {
		let r = await g("UNIT 19 - 11000 8 St, Dawson Creek, V1G 4K6, british columbia, canada");
		return postgres.query(
			`select ios_store_id(
				'Dawson Creek',
				$1,
				$2,
				$3,
				$4,
				$5,
				$6,
				'https://www.dawsoncreekcannabis.co',
				$7,
				$8,
				$9,
				$10,
				$11,
				'2507190299',
				null,
				true
			)`,
			[r[0].region, r[0].country, r[0].address, r[0].address2, r[0].city, r[0].postal_code, r[1].lng, r[1].lat, r[3], r[4], r[2]]
		);
	});
(async function() {
	storeID = (await storeID).rows[0].ios_store_id;
	products = await products;
	for(let i = 0; i < products.length; ++i) {
		if(products[i].barcode && products[i].price < 20000 && products[i].quantity >= 0) {
			persist(products[i].barcode, products[i].price, products[i].quantity);
		}
		for(let j = 0; j < products[i].variants.length; ++j) {
			if(products[i].variants[j].barcode && products[i].variants[j].price < 20000 && products[i].variants[j].quantity >= 0) {
				persist(products[i].variants[j].barcode, products[i].variants[j].price, products[i].variants[j].quantity);
			}
		}
	}
	for(let [key, value] of m) {
		//todo: other official government online stores
		//default concentrations from online stores with fixed prescedence. OCS seems to have the highest quality data
		await postgres.query(
			`insert into menu_item (variant_id, store_id, thc, cbd, price, stock)
			select
				variant_id,
				$4,
				thc,
				cbd,
				$2,
				$3
			from
				variant_identifier
				inner join menu_item using (variant_id)
				inner join store using (store_id)
			where
				gtin = $1 and
				address is null and address2 is null and city is null and postal_code is null and longitude is null and latitude is null and country = 'canada' and
				(
					joined_name = 'ocs' and region = 'ontario' or
					joined_name = 'bc' and region = 'british columbia' or
					joined_name = 'alberta' and region = 'alberta'
				)
			limit 1
			on conflict (variant_id, store_id) do update
			set
				price = excluded.price,
				stock = excluded.stock
			where
				menu_item.price != excluded.price and
				menu_item.stock != excluded.stock`,
			[key, ...value, storeID]
		);
	}
	await postgres.query(
		'delete from menu_item where store_id = $2 and variant_id not in (select variant_id from variant_identifier where gtin = any($1))',
		[Array.from(m.keys()), storeID]
	);
	await postgres.query('commit');
	await postgres.end();
})();