"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.archiveProduct = exports.updateProduct = exports.createProduct = exports.getProductById = exports.getProductBySlug = exports.listProducts = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const index_js_1 = require("../db/index.js");
const schema_js_1 = require("../db/schema.js");
const productSerializers_js_1 = require("./productSerializers.js");
const productSelect = {
    product: {
        id: schema_js_1.products.id,
        sku: schema_js_1.products.sku,
        name: schema_js_1.products.name,
        slug: schema_js_1.products.slug,
        description: schema_js_1.products.description,
        basePrice: schema_js_1.products.basePrice,
        discountPercent: schema_js_1.products.discountPercent,
        salePrice: schema_js_1.products.salePrice,
        stockQuantity: schema_js_1.products.stockQuantity,
        status: schema_js_1.products.status,
        isFeatured: schema_js_1.products.isFeatured,
        averageRating: schema_js_1.products.averageRating,
        ratingCount: schema_js_1.products.ratingCount,
        createdAt: schema_js_1.products.createdAt,
        updatedAt: schema_js_1.products.updatedAt,
    },
    brand: {
        id: schema_js_1.brands.id,
        name: schema_js_1.brands.name,
        slug: schema_js_1.brands.slug,
    },
    productType: {
        id: schema_js_1.productTypes.id,
        name: schema_js_1.productTypes.name,
        slug: schema_js_1.productTypes.slug,
    },
    collection: {
        id: schema_js_1.collections.id,
        name: schema_js_1.collections.name,
        slug: schema_js_1.collections.slug,
    },
    frameShape: {
        id: schema_js_1.frameShapes.id,
        name: schema_js_1.frameShapes.name,
        slug: schema_js_1.frameShapes.slug,
    },
    frameColor: {
        id: schema_js_1.frameColors.id,
        name: schema_js_1.frameColors.name,
        slug: schema_js_1.frameColors.slug,
        hexCode: schema_js_1.frameColors.hexCode,
    },
    ageGroup: {
        id: schema_js_1.ageGroups.id,
        name: schema_js_1.ageGroups.name,
        slug: schema_js_1.ageGroups.slug,
    },
    size: {
        id: schema_js_1.sizes.id,
        name: schema_js_1.sizes.name,
        slug: schema_js_1.sizes.slug,
    },
};
const productBaseQuery = () => index_js_1.db
    .select(productSelect)
    .from(schema_js_1.products)
    .leftJoin(schema_js_1.brands, (0, drizzle_orm_1.eq)(schema_js_1.products.brandId, schema_js_1.brands.id))
    .leftJoin(schema_js_1.productTypes, (0, drizzle_orm_1.eq)(schema_js_1.products.productTypeId, schema_js_1.productTypes.id))
    .leftJoin(schema_js_1.collections, (0, drizzle_orm_1.eq)(schema_js_1.products.collectionId, schema_js_1.collections.id))
    .leftJoin(schema_js_1.frameShapes, (0, drizzle_orm_1.eq)(schema_js_1.products.frameShapeId, schema_js_1.frameShapes.id))
    .leftJoin(schema_js_1.frameColors, (0, drizzle_orm_1.eq)(schema_js_1.products.frameColorId, schema_js_1.frameColors.id))
    .leftJoin(schema_js_1.ageGroups, (0, drizzle_orm_1.eq)(schema_js_1.products.ageGroupId, schema_js_1.ageGroups.id))
    .leftJoin(schema_js_1.sizes, (0, drizzle_orm_1.eq)(schema_js_1.products.sizeId, schema_js_1.sizes.id));
const productCountQuery = () => index_js_1.db
    .select({ total: (0, drizzle_orm_1.count)() })
    .from(schema_js_1.products)
    .leftJoin(schema_js_1.brands, (0, drizzle_orm_1.eq)(schema_js_1.products.brandId, schema_js_1.brands.id))
    .leftJoin(schema_js_1.productTypes, (0, drizzle_orm_1.eq)(schema_js_1.products.productTypeId, schema_js_1.productTypes.id))
    .leftJoin(schema_js_1.collections, (0, drizzle_orm_1.eq)(schema_js_1.products.collectionId, schema_js_1.collections.id))
    .leftJoin(schema_js_1.frameShapes, (0, drizzle_orm_1.eq)(schema_js_1.products.frameShapeId, schema_js_1.frameShapes.id))
    .leftJoin(schema_js_1.frameColors, (0, drizzle_orm_1.eq)(schema_js_1.products.frameColorId, schema_js_1.frameColors.id))
    .leftJoin(schema_js_1.ageGroups, (0, drizzle_orm_1.eq)(schema_js_1.products.ageGroupId, schema_js_1.ageGroups.id))
    .leftJoin(schema_js_1.sizes, (0, drizzle_orm_1.eq)(schema_js_1.products.sizeId, schema_js_1.sizes.id));
const getIdsBySlugs = async (table, slugs) => {
    if (!slugs || slugs.length === 0)
        return undefined;
    const rows = await index_js_1.db
        .select({ id: table.id })
        .from(table)
        .where((0, drizzle_orm_1.inArray)(table.slug, slugs));
    return rows.map((row) => row.id);
};
const existsRelation = (relationTable, productIdColumn, relationIdColumn, ids) => {
    if (!ids || ids.length === 0)
        return undefined;
    return (0, drizzle_orm_1.sql) `exists (select 1 from ${relationTable} where ${productIdColumn} = ${schema_js_1.products.id} and ${(0, drizzle_orm_1.inArray)(relationIdColumn, ids)})`;
};
const buildWhereConditions = async (query, includeAllStatuses) => {
    const conditions = [];
    if (includeAllStatuses) {
        if (query.status?.length)
            conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.products.status, query.status));
    }
    else {
        conditions.push((0, drizzle_orm_1.eq)(schema_js_1.products.status, "active"));
    }
    if (query.q) {
        const pattern = `%${query.q}%`;
        conditions.push((0, drizzle_orm_1.or)((0, drizzle_orm_1.like)(schema_js_1.products.name, pattern), (0, drizzle_orm_1.like)(schema_js_1.products.sku, pattern), (0, drizzle_orm_1.like)(schema_js_1.products.description, pattern)));
    }
    if (query.brand?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.brands.slug, query.brand));
    if (query.type?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.productTypes.slug, query.type));
    if (query.collection?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.collections.slug, query.collection));
    if (query.frameShape?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.frameShapes.slug, query.frameShape));
    if (query.color?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.frameColors.slug, query.color));
    if (query.ageGroup?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.ageGroups.slug, query.ageGroup));
    if (query.size?.length)
        conditions.push((0, drizzle_orm_1.inArray)(schema_js_1.sizes.slug, query.size));
    if (query.minPrice !== undefined)
        conditions.push((0, drizzle_orm_1.gte)(schema_js_1.products.salePrice, query.minPrice));
    if (query.maxPrice !== undefined)
        conditions.push((0, drizzle_orm_1.lte)(schema_js_1.products.salePrice, query.maxPrice));
    if (query.rating !== undefined)
        conditions.push((0, drizzle_orm_1.gte)(schema_js_1.products.averageRating, query.rating.toFixed(2)));
    if (query.inStock === true)
        conditions.push((0, drizzle_orm_1.gt)(schema_js_1.products.stockQuantity, 0));
    if (query.inStock === false)
        conditions.push((0, drizzle_orm_1.eq)(schema_js_1.products.stockQuantity, 0));
    if (query.featured !== undefined)
        conditions.push((0, drizzle_orm_1.eq)(schema_js_1.products.isFeatured, query.featured));
    const [genderIds, faceShapeIds, lensFeatureIds, occasionIds] = await Promise.all([
        getIdsBySlugs(schema_js_1.genders, query.gender),
        getIdsBySlugs(schema_js_1.faceShapes, query.faceShape),
        getIdsBySlugs(schema_js_1.lensFeatures, query.lens),
        getIdsBySlugs(schema_js_1.occasions, query.occasion),
    ]);
    if (query.gender?.length && genderIds?.length === 0)
        conditions.push((0, drizzle_orm_1.sql) `false`);
    if (query.faceShape?.length && faceShapeIds?.length === 0)
        conditions.push((0, drizzle_orm_1.sql) `false`);
    if (query.lens?.length && lensFeatureIds?.length === 0)
        conditions.push((0, drizzle_orm_1.sql) `false`);
    if (query.occasion?.length && occasionIds?.length === 0)
        conditions.push((0, drizzle_orm_1.sql) `false`);
    const genderCondition = existsRelation(schema_js_1.productGenders, schema_js_1.productGenders.productId, schema_js_1.productGenders.genderId, genderIds);
    const faceShapeCondition = existsRelation(schema_js_1.productFaceShapes, schema_js_1.productFaceShapes.productId, schema_js_1.productFaceShapes.faceShapeId, faceShapeIds);
    const lensCondition = existsRelation(schema_js_1.productLensFeatures, schema_js_1.productLensFeatures.productId, schema_js_1.productLensFeatures.lensFeatureId, lensFeatureIds);
    const occasionCondition = existsRelation(schema_js_1.productOccasions, schema_js_1.productOccasions.productId, schema_js_1.productOccasions.occasionId, occasionIds);
    if (genderCondition)
        conditions.push(genderCondition);
    if (faceShapeCondition)
        conditions.push(faceShapeCondition);
    if (lensCondition)
        conditions.push(lensCondition);
    if (occasionCondition)
        conditions.push(occasionCondition);
    return conditions.length ? (0, drizzle_orm_1.and)(...conditions) : undefined;
};
const getOrderBy = (sort) => {
    switch (sort) {
        case "oldest":
            return [(0, drizzle_orm_1.asc)(schema_js_1.products.createdAt), (0, drizzle_orm_1.asc)(schema_js_1.products.id)];
        case "price_asc":
            return [(0, drizzle_orm_1.asc)(schema_js_1.products.salePrice), (0, drizzle_orm_1.desc)(schema_js_1.products.id)];
        case "price_desc":
            return [(0, drizzle_orm_1.desc)(schema_js_1.products.salePrice), (0, drizzle_orm_1.desc)(schema_js_1.products.id)];
        case "rating_desc":
            return [
                (0, drizzle_orm_1.desc)(schema_js_1.products.averageRating),
                (0, drizzle_orm_1.desc)(schema_js_1.products.ratingCount),
                (0, drizzle_orm_1.desc)(schema_js_1.products.id),
            ];
        case "popular":
            return [
                (0, drizzle_orm_1.desc)(schema_js_1.products.ratingCount),
                (0, drizzle_orm_1.desc)(schema_js_1.products.averageRating),
                (0, drizzle_orm_1.desc)(schema_js_1.products.id),
            ];
        case "name_asc":
            return [(0, drizzle_orm_1.asc)(schema_js_1.products.name), (0, drizzle_orm_1.asc)(schema_js_1.products.id)];
        case "newest":
        default:
            return [(0, drizzle_orm_1.desc)(schema_js_1.products.createdAt), (0, drizzle_orm_1.desc)(schema_js_1.products.id)];
    }
};
const getMediaByProductIds = async (productIds) => {
    if (productIds.length === 0)
        return new Map();
    const rows = await index_js_1.db
        .select({
        ownerId: schema_js_1.mediaAssets.ownerId,
        id: schema_js_1.mediaAssets.id,
        url: schema_js_1.mediaAssets.url,
        altText: schema_js_1.mediaAssets.altText,
        isPrimary: schema_js_1.mediaAssets.isPrimary,
        sortOrder: schema_js_1.mediaAssets.sortOrder,
    })
        .from(schema_js_1.mediaAssets)
        .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.mediaAssets.ownerType, "product"), (0, drizzle_orm_1.inArray)(schema_js_1.mediaAssets.ownerId, productIds)))
        .orderBy((0, drizzle_orm_1.desc)(schema_js_1.mediaAssets.isPrimary), (0, drizzle_orm_1.asc)(schema_js_1.mediaAssets.sortOrder), (0, drizzle_orm_1.asc)(schema_js_1.mediaAssets.id));
    const map = new Map();
    for (const row of rows) {
        const entry = {
            id: row.id,
            url: row.url,
            altText: row.altText,
            isPrimary: row.isPrimary,
            sortOrder: row.sortOrder,
        };
        const existing = map.get(row.ownerId);
        if (existing) {
            existing.push(entry);
        }
        else {
            map.set(row.ownerId, [entry]);
        }
    }
    return map;
};
const listProducts = async (query, options = {}) => {
    const includeAllStatuses = options.includeAllStatuses === true;
    const where = await buildWhereConditions(query, includeAllStatuses);
    const offset = (query.page - 1) * query.perPage;
    const [countRows, productRows] = await Promise.all([
        productCountQuery().where(where),
        productBaseQuery()
            .where(where)
            .orderBy(...getOrderBy(query.sort))
            .limit(query.perPage)
            .offset(offset),
    ]);
    const total = countRows[0]?.total ?? 0;
    const mediaMap = await getMediaByProductIds(productRows.map((row) => row.product.id));
    const items = productRows.map((row) => {
        const productMedia = mediaMap.get(row.product.id) ?? [];
        return (0, productSerializers_js_1.toProductListItem)({
            ...row,
            primaryMedia: productMedia.find((m) => m.isPrimary) ?? productMedia[0] ?? null,
            media: productMedia,
        });
    });
    const totalPages = total === 0 ? 0 : Math.ceil(total / query.perPage);
    return {
        items,
        pagination: {
            page: query.page,
            perPage: query.perPage,
            total,
            totalPages,
            hasNextPage: query.page < totalPages,
            hasPreviousPage: query.page > 1,
        },
    };
};
exports.listProducts = listProducts;
const findProductRowBy = async (where) => {
    const [row] = await productBaseQuery().where(where).limit(1);
    if (!row)
        return null;
    const mediaMap = await getMediaByProductIds([row.product.id]);
    const productMedia = mediaMap.get(row.product.id) ?? [];
    return {
        ...row,
        primaryMedia: productMedia.find((m) => m.isPrimary) ?? productMedia[0] ?? null,
        media: productMedia,
    };
};
const getProductRelations = async (productId) => {
    const [media, genderRows, faceShapeRows, lensFeatureRows, occasionRows] = await Promise.all([
        index_js_1.db
            .select({
            id: schema_js_1.mediaAssets.id,
            url: schema_js_1.mediaAssets.url,
            altText: schema_js_1.mediaAssets.altText,
            isPrimary: schema_js_1.mediaAssets.isPrimary,
            sortOrder: schema_js_1.mediaAssets.sortOrder,
        })
            .from(schema_js_1.mediaAssets)
            .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.mediaAssets.ownerType, "product"), (0, drizzle_orm_1.eq)(schema_js_1.mediaAssets.ownerId, productId)))
            .orderBy((0, drizzle_orm_1.desc)(schema_js_1.mediaAssets.isPrimary), (0, drizzle_orm_1.asc)(schema_js_1.mediaAssets.sortOrder), (0, drizzle_orm_1.asc)(schema_js_1.mediaAssets.id)),
        index_js_1.db
            .select({ id: schema_js_1.genders.id, name: schema_js_1.genders.name, slug: schema_js_1.genders.slug })
            .from(schema_js_1.productGenders)
            .innerJoin(schema_js_1.genders, (0, drizzle_orm_1.eq)(schema_js_1.productGenders.genderId, schema_js_1.genders.id))
            .where((0, drizzle_orm_1.eq)(schema_js_1.productGenders.productId, productId))
            .orderBy((0, drizzle_orm_1.asc)(schema_js_1.genders.name)),
        index_js_1.db
            .select({
            id: schema_js_1.faceShapes.id,
            name: schema_js_1.faceShapes.name,
            slug: schema_js_1.faceShapes.slug,
        })
            .from(schema_js_1.productFaceShapes)
            .innerJoin(schema_js_1.faceShapes, (0, drizzle_orm_1.eq)(schema_js_1.productFaceShapes.faceShapeId, schema_js_1.faceShapes.id))
            .where((0, drizzle_orm_1.eq)(schema_js_1.productFaceShapes.productId, productId))
            .orderBy((0, drizzle_orm_1.asc)(schema_js_1.faceShapes.name)),
        index_js_1.db
            .select({
            id: schema_js_1.lensFeatures.id,
            name: schema_js_1.lensFeatures.name,
            slug: schema_js_1.lensFeatures.slug,
        })
            .from(schema_js_1.productLensFeatures)
            .innerJoin(schema_js_1.lensFeatures, (0, drizzle_orm_1.eq)(schema_js_1.productLensFeatures.lensFeatureId, schema_js_1.lensFeatures.id))
            .where((0, drizzle_orm_1.eq)(schema_js_1.productLensFeatures.productId, productId))
            .orderBy((0, drizzle_orm_1.asc)(schema_js_1.lensFeatures.name)),
        index_js_1.db
            .select({
            id: schema_js_1.occasions.id,
            name: schema_js_1.occasions.name,
            slug: schema_js_1.occasions.slug,
        })
            .from(schema_js_1.productOccasions)
            .innerJoin(schema_js_1.occasions, (0, drizzle_orm_1.eq)(schema_js_1.productOccasions.occasionId, schema_js_1.occasions.id))
            .where((0, drizzle_orm_1.eq)(schema_js_1.productOccasions.productId, productId))
            .orderBy((0, drizzle_orm_1.asc)(schema_js_1.occasions.name)),
    ]);
    return {
        media,
        genders: genderRows,
        faceShapes: faceShapeRows,
        lensFeatures: lensFeatureRows,
        occasions: occasionRows,
    };
};
const getProductBySlug = async (slug, includeAllStatuses = false) => {
    const statusCondition = includeAllStatuses
        ? undefined
        : (0, drizzle_orm_1.eq)(schema_js_1.products.status, "active");
    const row = await findProductRowBy((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.products.slug, slug), ...(statusCondition ? [statusCondition] : [])));
    if (!row)
        return null;
    return (0, productSerializers_js_1.toProductDetail)(row, await getProductRelations(row.product.id));
};
exports.getProductBySlug = getProductBySlug;
const getProductById = async (id) => {
    const row = await findProductRowBy((0, drizzle_orm_1.eq)(schema_js_1.products.id, id));
    if (!row)
        return null;
    return (0, productSerializers_js_1.toProductDetail)(row, await getProductRelations(row.product.id));
};
exports.getProductById = getProductById;
const insertRelations = async (tx, productId, input) => {
    if (input.genderIds.length) {
        await tx
            .insert(schema_js_1.productGenders)
            .values(input.genderIds.map((genderId) => ({ productId, genderId })));
    }
    if (input.faceShapeIds.length) {
        await tx
            .insert(schema_js_1.productFaceShapes)
            .values(input.faceShapeIds.map((faceShapeId) => ({ productId, faceShapeId })));
    }
    if (input.lensFeatureIds.length) {
        await tx
            .insert(schema_js_1.productLensFeatures)
            .values(input.lensFeatureIds.map((lensFeatureId) => ({
            productId,
            lensFeatureId,
        })));
    }
    if (input.occasionIds.length) {
        await tx
            .insert(schema_js_1.productOccasions)
            .values(input.occasionIds.map((occasionId) => ({ productId, occasionId })));
    }
};
const insertMedia = async (tx, productId, media, uploadedByStaffId) => {
    if (!media.length)
        return;
    const hasPrimary = media.some((item) => item.isPrimary);
    await tx.insert(schema_js_1.mediaAssets).values(media.map((item, index) => ({
        ownerType: "product",
        ownerId: productId,
        url: item.url,
        storageKey: item.storageKey,
        fileName: item.fileName,
        mimeType: item.mimeType,
        sizeBytes: item.sizeBytes,
        altText: item.altText,
        sortOrder: item.sortOrder,
        isPrimary: hasPrimary ? item.isPrimary : index === 0,
        uploadedByStaffId,
    })));
};
const createProduct = async (input, uploadedByStaffId) => {
    const finalSlug = input.slug ?? (0, productSerializers_js_1.slugify)(input.name);
    const finalSalePrice = input.salePrice ??
        (0, productSerializers_js_1.calculateSalePrice)(input.basePrice, input.discountPercent);
    await index_js_1.db.transaction(async (tx) => {
        await tx.insert(schema_js_1.products).values({
            sku: input.sku,
            name: input.name,
            slug: finalSlug,
            description: input.description,
            brandId: input.brandId,
            productTypeId: input.productTypeId,
            collectionId: input.collectionId,
            frameShapeId: input.frameShapeId,
            frameColorId: input.frameColorId,
            ageGroupId: input.ageGroupId,
            sizeId: input.sizeId,
            basePrice: input.basePrice,
            discountPercent: input.discountPercent,
            salePrice: finalSalePrice,
            stockQuantity: input.stockQuantity,
            status: input.status,
            isFeatured: input.isFeatured,
        });
        const [created] = await tx
            .select({ id: schema_js_1.products.id })
            .from(schema_js_1.products)
            .where((0, drizzle_orm_1.eq)(schema_js_1.products.slug, finalSlug))
            .limit(1);
        if (!created)
            throw new Error("Product creation failed.");
        await insertRelations(tx, created.id, input);
        await insertMedia(tx, created.id, input.media, uploadedByStaffId);
    });
    const product = await (0, exports.getProductBySlug)(finalSlug, true);
    if (!product)
        throw new Error("Product creation failed.");
    return product;
};
exports.createProduct = createProduct;
const replaceRelation = async (tx, table, productIdColumn, relationIdColumnName, productId, ids) => {
    if (ids === undefined)
        return;
    await tx.delete(table).where((0, drizzle_orm_1.eq)(productIdColumn, productId));
    if (ids.length === 0)
        return;
    await tx
        .insert(table)
        .values(ids.map((relationId) => ({
        productId,
        [relationIdColumnName]: relationId,
    })));
};
const updateProduct = async (productId, input, uploadedByStaffId) => {
    const updateValues = {};
    if (input.sku !== undefined)
        updateValues.sku = input.sku;
    if (input.name !== undefined)
        updateValues.name = input.name;
    if (input.slug !== undefined)
        updateValues.slug = input.slug;
    if (input.description !== undefined)
        updateValues.description = input.description;
    if (input.brandId !== undefined)
        updateValues.brandId = input.brandId;
    if (input.productTypeId !== undefined)
        updateValues.productTypeId = input.productTypeId;
    if (input.collectionId !== undefined)
        updateValues.collectionId = input.collectionId;
    if (input.frameShapeId !== undefined)
        updateValues.frameShapeId = input.frameShapeId;
    if (input.frameColorId !== undefined)
        updateValues.frameColorId = input.frameColorId;
    if (input.ageGroupId !== undefined)
        updateValues.ageGroupId = input.ageGroupId;
    if (input.sizeId !== undefined)
        updateValues.sizeId = input.sizeId;
    if (input.basePrice !== undefined)
        updateValues.basePrice = input.basePrice;
    if (input.discountPercent !== undefined)
        updateValues.discountPercent = input.discountPercent;
    if (input.stockQuantity !== undefined)
        updateValues.stockQuantity = input.stockQuantity;
    if (input.status !== undefined)
        updateValues.status = input.status;
    if (input.isFeatured !== undefined)
        updateValues.isFeatured = input.isFeatured;
    const current = await (0, exports.getProductById)(productId);
    if (!current)
        return null;
    if (input.salePrice !== undefined) {
        updateValues.salePrice = input.salePrice;
    }
    else if (input.basePrice !== undefined ||
        input.discountPercent !== undefined) {
        updateValues.salePrice = (0, productSerializers_js_1.calculateSalePrice)(input.basePrice ?? current.basePrice, input.discountPercent ?? current.discountPercent);
    }
    await index_js_1.db.transaction(async (tx) => {
        if (Object.keys(updateValues).length > 0) {
            await tx
                .update(schema_js_1.products)
                .set(updateValues)
                .where((0, drizzle_orm_1.eq)(schema_js_1.products.id, productId));
        }
        await replaceRelation(tx, schema_js_1.productGenders, schema_js_1.productGenders.productId, "genderId", productId, input.genderIds);
        await replaceRelation(tx, schema_js_1.productFaceShapes, schema_js_1.productFaceShapes.productId, "faceShapeId", productId, input.faceShapeIds);
        await replaceRelation(tx, schema_js_1.productLensFeatures, schema_js_1.productLensFeatures.productId, "lensFeatureId", productId, input.lensFeatureIds);
        await replaceRelation(tx, schema_js_1.productOccasions, schema_js_1.productOccasions.productId, "occasionId", productId, input.occasionIds);
        if (input.media !== undefined) {
            await tx
                .delete(schema_js_1.mediaAssets)
                .where((0, drizzle_orm_1.and)((0, drizzle_orm_1.eq)(schema_js_1.mediaAssets.ownerType, "product"), (0, drizzle_orm_1.eq)(schema_js_1.mediaAssets.ownerId, productId)));
            await insertMedia(tx, productId, input.media, uploadedByStaffId);
        }
    });
    return (0, exports.getProductById)(productId);
};
exports.updateProduct = updateProduct;
const archiveProduct = async (productId) => {
    const existing = await (0, exports.getProductById)(productId);
    if (!existing)
        return null;
    await index_js_1.db
        .update(schema_js_1.products)
        .set({ status: "archived" })
        .where((0, drizzle_orm_1.eq)(schema_js_1.products.id, productId));
    return (0, exports.getProductById)(productId);
};
exports.archiveProduct = archiveProduct;
//# sourceMappingURL=productService.js.map