import { and, eq } from "drizzle-orm";
import type { db as prodDb } from "../../db/index.ts";
import { globalItems, marketPrices } from "../../db/schema.ts";

type Db = typeof prodDb;

export async function getMarketPrices(db: Db, globalItemId: number) {
	return db
		.select()
		.from(marketPrices)
		.where(eq(marketPrices.globalItemId, globalItemId))
		.orderBy(marketPrices.market);
}

export async function getMarketPricesForMarket(
	db: Db,
	globalItemId: number,
	market: string,
) {
	return db
		.select()
		.from(marketPrices)
		.where(
			and(
				eq(marketPrices.globalItemId, globalItemId),
				eq(marketPrices.market, market),
			),
		);
}

export async function upsertMarketPrice(
	db: Db,
	data: {
		globalItemId: number;
		market: string;
		currency: string;
		priceCents: number;
		source?: string;
	},
) {
	// Verify global item exists
	const [gi] = await db
		.select({ id: globalItems.id })
		.from(globalItems)
		.where(eq(globalItems.id, data.globalItemId));
	if (!gi) return null;

	const [row] = await db
		.insert(marketPrices)
		.values({
			globalItemId: data.globalItemId,
			market: data.market,
			currency: data.currency,
			priceCents: data.priceCents,
			source: data.source ?? null,
		})
		.onConflictDoUpdate({
			target: [
				marketPrices.globalItemId,
				marketPrices.market,
				marketPrices.currency,
			],
			set: {
				priceCents: data.priceCents,
				source: data.source ?? null,
			},
		})
		.returning();

	return row;
}
