import { createHash } from 'node:crypto'; import type { Pool } from 'pg'; import type { DiscoveredProduct, NormalizedMarketProduct, ProductSourceSnapshot } from './types.ts'; function publicProductId(product: NormalizedMarketProduct) { const sourcePrefix = product.source === 'mvideo' ? 'mv' : 'ym'; if (product.sourceProductId) return `${sourcePrefix}_${product.sourceProductId}`; return `${sourcePrefix}_${Buffer.from(product.sourceUrl).toString('base64url').slice(0, 32)}`; } function valueHash(value: unknown) { return createHash('sha256').update(JSON.stringify(value)).digest('hex'); } function manufacturerSlug(name: string) { const slug = name .trim() .toLowerCase() .replace(/[^\p{Letter}\p{Number}]+/gu, '-') .replace(/^-+|-+$/g, ''); return slug || 'unknown'; } export class IngestionRepository { private readonly pool: Pool; constructor(pool: Pool) { this.pool = pool; } async recordSnapshot(snapshot: ProductSourceSnapshot) { await this.pool.query( ` insert into source_snapshots ( source, url, fetched_at, http_status, raw_snapshot_hash, stable_content_hash, raw_html_path, parsed_json ) values ($1, $2, $3, $4, $5, $6, $7, $8) `, [ snapshot.source, snapshot.url, snapshot.fetchedAt, snapshot.httpStatus, snapshot.rawSnapshotHash, snapshot.stableContentHash ?? null, snapshot.rawHtmlPath ?? null, snapshot.parsedJson, ], ); } async recordDiscoveredProducts(products: DiscoveredProduct[]) { for (const product of products) { await this.pool.query( ` insert into product_sources ( source, url, source_product_id, category_url, title_preview, first_seen_at, updated_at, state ) values ($1, $2, $3, $4, $5, $6, now(), 'discovered') on conflict (source, url) do update set source_product_id = coalesce(product_sources.source_product_id, excluded.source_product_id), category_url = coalesce(excluded.category_url, product_sources.category_url), title_preview = coalesce(excluded.title_preview, product_sources.title_preview), updated_at = now() `, [ product.source, product.productUrl, product.sourceProductId ?? null, product.categoryUrl ?? null, product.titlePreview ?? null, product.discoveredAt, ], ); } } async upsertNormalizedProduct(product: NormalizedMarketProduct, stableContentHash: string, fetchedAt: string) { const sourceScopedProductId = publicProductId(product); const matchingProduct = await this.pool.query<{ id: string }>( ` select id from products where lower(canonical_name) = lower($1) and id <> $2 order by discovered_at asc, id asc limit 1 `, [product.canonicalName, sourceScopedProductId], ); const productId = matchingProduct.rows[0]?.id ?? sourceScopedProductId; const linkedToExistingCanonicalProduct = productId !== sourceScopedProductId; const manufacturerId = await this.upsertManufacturer(product.brand); await this.pool.query( ` insert into products (id, manufacturer_id, brand, model, canonical_name, title, moderation_status, discovered_at, updated_at) values ($1, $2, $3, $4, $5, $6, 'needs_review', $7, $7) on conflict (id) do update set manufacturer_id = excluded.manufacturer_id, brand = excluded.brand, model = case when products.model_override then products.model else excluded.model end, canonical_name = case when products.canonical_name_override then products.canonical_name else excluded.canonical_name end, title = excluded.title, updated_at = excluded.updated_at `, [productId, manufacturerId, product.brand, product.canonicalModel, product.canonicalName, product.title, fetchedAt], ); await this.pool.query( ` insert into product_sources ( product_id, source, url, source_product_id, stable_content_hash, last_fetched_at, parsed_json, state, updated_at ) values ($1, $2, $3, $4, $5, $6, $7, 'parsed', now()) on conflict (source, url) do update set product_id = excluded.product_id, source_product_id = coalesce(product_sources.source_product_id, excluded.source_product_id), stable_content_hash = excluded.stable_content_hash, last_fetched_at = excluded.last_fetched_at, parsed_json = excluded.parsed_json, state = excluded.state, updated_at = now() `, [productId, product.source, product.sourceUrl, product.sourceProductId ?? null, stableContentHash, fetchedAt, product], ); for (const [key, value] of Object.entries(product.specs)) { await this.pool.query( ` insert into product_specs (product_id, key, value, updated_at) values ($1, $2, $3, now()) on conflict (product_id, key) do update set value = excluded.value, updated_at = now() `, [productId, key, JSON.stringify(value)], ); } await this.pool.query( ` delete from product_source_specs where product_id = $1 and source = $2 and source_url = $3 `, [productId, product.source, product.sourceUrl], ); for (const spec of product.rawSpecs) { const comparableValue = spec.normalizedValue ?? spec.value; await this.pool.query( ` insert into product_source_specs ( product_id, source, source_url, source_product_id, raw_group, raw_label, raw_value, normalized_key, normalized_value, value_hash, fetched_at ) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) on conflict (product_id, source, source_url, raw_label) do update set raw_group = excluded.raw_group, raw_value = excluded.raw_value, normalized_key = excluded.normalized_key, normalized_value = excluded.normalized_value, value_hash = excluded.value_hash, fetched_at = excluded.fetched_at, updated_at = now() `, [ productId, product.source, product.sourceUrl, product.sourceProductId ?? null, spec.group ?? null, spec.label, JSON.stringify(spec.value), spec.normalizedKey ?? null, spec.normalizedValue === undefined ? null : JSON.stringify(spec.normalizedValue), valueHash(comparableValue), fetchedAt, ], ); } await this.refreshSpecConflicts(productId); for (const imageUrl of product.images) { await this.pool.query( ` insert into product_images (product_id, original_url, source, status) values ($1, $2, $3, 'needs_review') on conflict (product_id, original_url) do nothing `, [productId, imageUrl, product.source], ); } if (product.aggregateRating) { await this.pool.query( ` insert into source_ratings (product_id, source, source_product_id, rating_value, rating_scale, rating_count, fetched_at) values ($1, $2, $3, $4, $5, $6, $7) `, [ productId, product.source, product.sourceProductId ?? null, product.aggregateRating.value, product.aggregateRating.scale ?? null, product.aggregateRating.ratingCount ?? null, fetchedAt, ], ); } await this.pool.query( ` insert into moderation_queue (product_id, reason, state) values ($1, $2, 'pending') on conflict (product_id, reason) do nothing `, [productId, linkedToExistingCanonicalProduct ? 'same_product' : 'new_product'], ); return productId; } private async upsertManufacturer(name: string) { const result = await this.pool.query<{ id: string }>( ` insert into manufacturers (slug, name) values ($1, $2) on conflict (slug) do update set name = excluded.name, updated_at = now() returning id `, [manufacturerSlug(name), name], ); return result.rows[0].id; } private async refreshSpecConflicts(productId: string) { await this.pool.query( ` update moderation_conflicts set state = 'resolved', updated_at = now() where product_id = $1 and conflict_type = 'spec_value' `, [productId], ); const conflicts = await this.pool.query<{ normalized_key: string; values_json: unknown; }>( ` select normalized_key, jsonb_agg( jsonb_build_object( 'source', source, 'url', source_url, 'sourceProductId', source_product_id, 'value', coalesce(normalized_value, raw_value), 'rawLabel', raw_label, 'rawGroup', raw_group ) order by source, source_url, raw_label ) as values_json from product_source_specs where product_id = $1 and normalized_key is not null group by normalized_key having count(distinct value_hash) > 1 `, [productId], ); for (const conflict of conflicts.rows) { await this.pool.query( ` insert into moderation_conflicts (product_id, conflict_type, key, values_json, state) values ($1, 'spec_value', $2, $3, 'pending') on conflict (product_id, conflict_type, key) do update set values_json = excluded.values_json, state = 'pending', updated_at = now() `, [productId, conflict.normalized_key, JSON.stringify(conflict.values_json)], ); } if (conflicts.rowCount) { await this.pool.query( ` insert into moderation_queue (product_id, reason, state) values ($1, 'conflicting_specs', 'pending') on conflict (product_id, reason) do update set state = 'pending', updated_at = now() `, [productId], ); } } }