All files / src/services/db flyer.db.ts

54.37% Statements 429/789
73.83% Branches 79/107
75.75% Functions 25/33
53.74% Lines 359/668

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 6692x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 76x 2x 2x 2x 2x 4x 4x 4x 4x 4x 9x 4x 9x 4x 4x 4x 4x 4x 8x 2x 2x 2x 2x 2x 2x 8x 2x     7x     2x           4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 17x 2x 2x   2x 2x 17x 17x 2x 17x   17x 17x     17x 14x     2x 2x 2x 2x 17x 12x 12x 2x 17x 2x 2x 2x 2x 17x 2x 17x 2x 2x 2x 2x 2x 2x 2x 17x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 17x 2x 2x 2x 2x 17x 7x 2x 2x 7x 7x 7x 2x 2x 7x 7x   7x           7x           7x   10x 10x 10x     10x 2x                           10x 2x   8x 2x 6x 4x 4x 4x 10x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 10x 2x 2x 2x 8x 8x 8x 2x 8x 10x 2x 2x 2x 2x 2x 2x 10x   10x                       8x   4x 4x 4x 4x 4x 4x 8x 4x 4x     8x 5x   3x                                     3x   4x 4x 4x 4x 4x 4x       3x 2x   1x                                         4x                                                                                 4x 4x 4x 4x 4x 4x 4x               4x 4x 1x                     7x   7x     5x 5x                                                                                               4x 4x 4x 4x 4x 4x 5x 4x   1x                                           7x   7x 4x 4x 6x 6x 4x     5x   1x                                 4x 4x 4x 4x 5x 5x       4x   1x                             4x 4x 4x 5x 5x 4x 1x 4x 1x 1x 1x 3x   1x             1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 14x 14x     13x   1x                           4x 4x 4x 4x 4x 4x 4x     3x     3x   3x         3x   1x               2x 2x 2x 2x 2x 2x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 2x 2x 5x 2x 2x 5x 2x 2x 5x 2x 2x 4x 2x 4x 2x  
// src/services/db/flyer.db.ts
import type { Pool, PoolClient } from 'pg';
import { getPool, withTransaction } from './connection.db';
import type { Logger } from 'pino';
import { NotFoundError, handleDbError } from './errors.db';
import { cacheService, CACHE_TTL, CACHE_PREFIX } from '../cacheService.server';
import type {
  Flyer,
  FlyerItem,
  FlyerInsert,
  FlyerItemInsert,
  Brand,
  FlyerDbInsert,
} from '../../types';
 
export class FlyerRepository {
  // The repository only needs an object with a `query` method, matching the Pool/PoolClient interface.
  // Using `Pick` makes this dependency explicit and simplifies testing by reducing the mock surface.
  private db: Pick<Pool | PoolClient, 'query'>;
 
  constructor(db: Pick<Pool | PoolClient, 'query'> = getPool()) {
    this.db = db;
  }
 
  /**
   * Finds a store by name, or creates it if it doesn't exist.
   * This method is designed to be safe for concurrent calls.
   * @param storeName The name of the store.
   * @returns A promise that resolves to the store's ID.
   */
  async findOrCreateStore(storeName: string, logger: Logger): Promise<number> {
    try {
      // Atomically insert the store if it doesn't exist. This is safe from race conditions.
      await this.db.query(
        'INSERT INTO public.stores (name) VALUES ($1) ON CONFLICT (name) DO NOTHING',
        [storeName],
      );
 
      // Now, the store is guaranteed to exist, so we can safely select its ID.
      const result = await this.db.query<{ store_id: number }>(
        'SELECT store_id FROM public.stores WHERE name = $1',
        [storeName],
      );
 
      // This case should be virtually impossible if the INSERT...ON CONFLICT logic is correct,
      // as it would mean the store was deleted between the two queries. We throw an error to be safe.
      if (result.rows.length === 0) {
        throw new Error('Failed to find store immediately after upsert operation.');
      }

      return result.rows[0].store_id;
    } catch (error) {
      // Use the centralized error handler for any unexpected database errors.
      handleDbError(
        error,
        logger,
        'Database error in findOrCreateStore',
        { storeName },
        {
          // Any error caught here is unexpected, so we use a generic message.
          defaultMessage: 'Failed to find or create store in database.',
        },
      );
    }
  }
 
  /**
   * Inserts a new flyer into the database.
   * @param flyerData - The data for the new flyer.
   * @returns The newly created flyer record with its ID.
   */
  async insertFlyer(flyerData: FlyerDbInsert, logger: Logger): Promise<Flyer> {
    console.error(
      '[DB DEBUG] FlyerRepository.insertFlyer called with:',
      JSON.stringify(flyerData, null, 2),
    );
    // Sanitize icon_url: Ensure empty strings become NULL to avoid regex constraint violations
    let iconUrl =
      flyerData.icon_url && flyerData.icon_url.trim() !== '' ? flyerData.icon_url : null;
    let imageUrl = flyerData.image_url || 'placeholder.jpg';
 
    try {
      // Fallback for tests/workers sending relative URLs to satisfy DB 'url_check' constraint
      const rawBaseUrl = process.env.FRONTEND_URL || 'https://example.com';
      const baseUrl = rawBaseUrl.endsWith('/') ? rawBaseUrl.slice(0, -1) : rawBaseUrl;

      // [DEBUG] Log URL transformation for debugging test failures
      if ((imageUrl && !imageUrl.startsWith('http')) || (iconUrl && !iconUrl.startsWith('http'))) {
        console.error('[DB DEBUG] Transforming relative URLs:', {
          baseUrl,
          originalImage: imageUrl,
          originalIcon: iconUrl,
        });
      }
 
      if (imageUrl && !imageUrl.startsWith('http')) {
        const cleanPath = imageUrl.startsWith('/') ? imageUrl.substring(1) : imageUrl;
        imageUrl = `${baseUrl}/${cleanPath}`;
      }
      if (iconUrl && !iconUrl.startsWith('http')) {
        const cleanPath = iconUrl.startsWith('/') ? iconUrl.substring(1) : iconUrl;
        iconUrl = `${baseUrl}/${cleanPath}`;
      }
 
      console.error('[DB DEBUG] Final URLs for insert:', { imageUrl, iconUrl });
 
      const query = `
        INSERT INTO flyers (
          file_name, image_url, icon_url, checksum, store_id, valid_from, valid_to, store_address,
          status, item_count, uploaded_by
        )
        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
        RETURNING *;
      `;
      const values = [
        flyerData.file_name, // $1
        imageUrl, // $2
        iconUrl, // $3
        flyerData.checksum, // $4
        flyerData.store_id, // $5
        flyerData.valid_from, // $6
        flyerData.valid_to, // $7
        flyerData.store_address, // $8
        flyerData.status, // $9
        flyerData.item_count, // $10
        flyerData.uploaded_by ?? null, // $11
      ];
 
      logger.debug(
        { query, values },
        '[DB insertFlyer] Executing insert with the following values.',
      );
 
      const result = await this.db.query<Flyer>(query, values);
      const newFlyer = result.rows[0];
 
      // Automatically populate flyer_locations if store_id is provided
      Eif (flyerData.store_id) {
        const { FlyerLocationRepository } = await import('./flyerLocation.db');
        const { Pool } = await import('pg');
 
        // Only pass the client if this.db is a PoolClient, not a Pool
        const clientToPass = this.db instanceof Pool ? undefined : (this.db as PoolClient);
        const flyerLocationRepo = new FlyerLocationRepository(clientToPass);

        await flyerLocationRepo.linkFlyerToAllStoreLocations(
          newFlyer.flyer_id,
          flyerData.store_id,
          logger,
        );

        logger.info(
          { flyerId: newFlyer.flyer_id, storeId: flyerData.store_id },
          'Auto-linked flyer to all store locations',
        );
      }

      return newFlyer;
    } catch (error) {
      console.error('[DB DEBUG] insertFlyer caught error:', error);
      const errorMessage = error instanceof Error ? error.message : '';
      let checkMsg = 'A database check constraint failed.';

      // [ENHANCED LOGGING]
      if (errorMessage.includes('url_check')) {
        logger.error(
          {
            error: errorMessage,
            offendingData: {
              image_url: flyerData.image_url,
              icon_url: flyerData.icon_url, // Log raw input
              sanitized_icon_url:
                flyerData.icon_url && flyerData.icon_url.trim() !== '' ? flyerData.icon_url : null,
            },
          },
          '[DB ERROR] URL Check Constraint Failed. Inspecting URLs.',
        );
      }

      if (errorMessage.includes('flyers_checksum_check')) {
        checkMsg =
          'The provided checksum is invalid or does not meet format requirements (e.g., must be a 64-character SHA-256 hash).';
      } else if (errorMessage.includes('flyers_status_check')) {
        checkMsg = 'Invalid status provided for flyer.';
      } else if (errorMessage.includes('url_check')) {
        checkMsg = `[URL_CHECK_FAIL] Invalid URL format. Image: '${imageUrl}', Icon: '${iconUrl}'`;
      }
 
      handleDbError(
        error,
        logger,
        'Database error in insertFlyer',
        { flyerData },
        {
          uniqueMessage: 'A flyer with this checksum already exists.',
          fkMessage: 'The specified user or store for this flyer does not exist.',
          checkMessage: checkMsg,
          defaultMessage: 'Failed to insert flyer into database.',
        },
      );
    }
  }
 
  /**
   * Inserts multiple flyer items into the database for a given flyer ID.
   * @param flyerId - The ID of the parent flyer.
   * @param items - An array of item data to insert.
   * @returns An array of the newly created flyer item records.
   */
  async insertFlyerItems(
    flyerId: number,
    items: FlyerItemInsert[],
    logger: Logger,
  ): Promise<FlyerItem[]> {
    try {
      if (!items || items.length === 0) {
        return [];
      }
 
      const values: (string | number | null)[] = [];
      const valueStrings: string[] = [];
      let paramIndex = 1;
 
      for (const item of items) {
        valueStrings.push(
          `($${paramIndex++}, $${paramIndex++}, $${paramIndex++}, $${paramIndex++}, $${paramIndex++}, $${paramIndex++}, $${paramIndex++}, $${paramIndex++})`,
        );
 
        // Sanitize price_display. The database requires a non-empty string.
        // We provide a default value if the input is null, undefined, or an empty string.
        const priceDisplay =
          item.price_display && item.price_display.trim() !== '' ? item.price_display : 'N/A';

        values.push(
          flyerId,
          item.item,
          priceDisplay,
          item.price_in_cents ?? null,
          item.quantity ?? '',
          item.category_name ?? null,
          item.view_count,
          item.click_count,
        );
      }

      const query = `
        INSERT INTO flyer_items (
          flyer_id, item, price_display, price_in_cents, quantity, category_name, view_count, click_count
        )
        VALUES ${valueStrings.join(', ')}
        RETURNING *;
      `;
 
      logger.debug(
        { query, values },
        '[DB insertFlyerItems] Executing bulk insert with the following values.',
      );

      const result = await this.db.query<FlyerItem>(query, values);
      return result.rows;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in insertFlyerItems',
        { flyerId },
        {
          fkMessage: 'The specified flyer, category, master item, or product does not exist.',
          defaultMessage: 'An unknown error occurred while inserting flyer items.',
        },
      );
    }
  }

  /**
   * Retrieves all distinct brands from the stores table.
   * Uses cache-aside pattern with 1-hour TTL (brands rarely change).
   * @returns A promise that resolves to an array of Brand objects.
   */
  async getAllBrands(logger: Logger): Promise<Brand[]> {
    const cacheKey = CACHE_PREFIX.BRANDS;

    return cacheService.getOrSet<Brand[]>(
      cacheKey,
      async () => {
        try {
          const query = `
            SELECT s.store_id as brand_id, s.name, s.logo_url, s.created_at, s.updated_at
            FROM public.stores s
            ORDER BY s.name;
          `;
          const res = await this.db.query<Brand>(query);
          return res.rows;
        } catch (error) {
          handleDbError(
            error,
            logger,
            'Database error in getAllBrands',
            {},
            {
              defaultMessage: 'Failed to retrieve brands from database.',
            },
          );
        }
      },
      { ttl: CACHE_TTL.BRANDS, logger },
    );
  }

  /**
   * Retrieves a single flyer by its ID.
   * @param flyerId The ID of the flyer to retrieve.
   * @returns A promise that resolves to the Flyer object or undefined if not found.
   */
  async getFlyerById(flyerId: number): Promise<Flyer> {
    const query = `
      SELECT
        f.*,
        -- Legacy store relationship (for backward compatibility)
        json_build_object(
          'store_id', s.store_id,
          'name', s.name,
          'logo_url', s.logo_url,
          'locations', COALESCE(
            (SELECT json_agg(
              json_build_object(
                'address_line_1', a.address_line_1,
                'city', a.city,
                'province_state', a.province_state,
                'postal_code', a.postal_code
              )
            )
            FROM public.store_locations sl
            JOIN public.addresses a ON sl.address_id = a.address_id
            WHERE sl.store_id = s.store_id),
            '[]'::json
          )
        ) as store,
        -- Correct many-to-many relationship via flyer_locations
        COALESCE(
          (SELECT json_agg(
            json_build_object(
              'store_location_id', fl_sl.store_location_id,
              'store', json_build_object(
                'store_id', fl_s.store_id,
                'name', fl_s.name,
                'logo_url', fl_s.logo_url
              ),
              'address', json_build_object(
                'address_id', fl_a.address_id,
                'address_line_1', fl_a.address_line_1,
                'address_line_2', fl_a.address_line_2,
                'city', fl_a.city,
                'province_state', fl_a.province_state,
                'postal_code', fl_a.postal_code,
                'country', fl_a.country
              )
            )
          )
          FROM public.flyer_locations fl
          JOIN public.store_locations fl_sl ON fl.store_location_id = fl_sl.store_location_id
          JOIN public.stores fl_s ON fl_sl.store_id = fl_s.store_id
          JOIN public.addresses fl_a ON fl_sl.address_id = fl_a.address_id
          WHERE fl.flyer_id = f.flyer_id),
          '[]'::json
        ) as locations
      FROM public.flyers f
      LEFT JOIN public.stores s ON f.store_id = s.store_id
      WHERE f.flyer_id = $1
    `;
    const res = await this.db.query<Flyer>(query, [flyerId]);
    if (res.rowCount === 0) throw new NotFoundError(`Flyer with ID ${flyerId} not found.`);
    return res.rows[0];
  }

  /**
   * Retrieves all flyers from the database, ordered by creation date.
   * Uses cache-aside pattern with 5-minute TTL.
   * @param limit The maximum number of flyers to return.
   * @param offset The number of flyers to skip.
   * @returns A promise that resolves to an array of Flyer objects.
   */
  async getFlyers(logger: Logger, limit: number = 20, offset: number = 0): Promise<Flyer[]> {
    const cacheKey = `${CACHE_PREFIX.FLYERS}:${limit}:${offset}`;

    return cacheService.getOrSet<Flyer[]>(
      cacheKey,
      async () => {
        try {
          const query = `
            SELECT
              f.*,
              -- Legacy store relationship (for backward compatibility)
              json_build_object(
                'store_id', s.store_id,
                'name', s.name,
                'logo_url', s.logo_url,
                'locations', COALESCE(
                  (SELECT json_agg(
                    json_build_object(
                      'address_line_1', a.address_line_1,
                      'city', a.city,
                      'province_state', a.province_state,
                      'postal_code', a.postal_code
                    )
                  )
                  FROM public.store_locations sl
                  JOIN public.addresses a ON sl.address_id = a.address_id
                  WHERE sl.store_id = s.store_id),
                  '[]'::json
                )
              ) as store,
              -- Correct many-to-many relationship via flyer_locations
              COALESCE(
                (SELECT json_agg(
                  json_build_object(
                    'store_location_id', fl_sl.store_location_id,
                    'store', json_build_object(
                      'store_id', fl_s.store_id,
                      'name', fl_s.name,
                      'logo_url', fl_s.logo_url
                    ),
                    'address', json_build_object(
                      'address_id', fl_a.address_id,
                      'address_line_1', fl_a.address_line_1,
                      'address_line_2', fl_a.address_line_2,
                      'city', fl_a.city,
                      'province_state', fl_a.province_state,
                      'postal_code', fl_a.postal_code,
                      'country', fl_a.country
                    )
                  )
                )
                FROM public.flyer_locations fl
                JOIN public.store_locations fl_sl ON fl.store_location_id = fl_sl.store_location_id
                JOIN public.stores fl_s ON fl_sl.store_id = fl_s.store_id
                JOIN public.addresses fl_a ON fl_sl.address_id = fl_a.address_id
                WHERE fl.flyer_id = f.flyer_id),
                '[]'::json
              ) as locations
            FROM public.flyers f
            JOIN public.stores s ON f.store_id = s.store_id
            ORDER BY f.created_at DESC LIMIT $1 OFFSET $2`;
          const res = await this.db.query<Flyer>(query, [limit, offset]);
          return res.rows;
        } catch (error) {
          handleDbError(
            error,
            logger,
            'Database error in getFlyers',
            { limit, offset },
            {
              defaultMessage: 'Failed to retrieve flyers from database.',
            },
          );
        }
      },
      { ttl: CACHE_TTL.FLYERS, logger },
    );
  }

  /**
   * Retrieves all items for a specific flyer.
   * Uses cache-aside pattern with 10-minute TTL.
   * @param flyerId The ID of the flyer.
   * @returns A promise that resolves to an array of FlyerItem objects.
   */
  async getFlyerItems(flyerId: number, logger: Logger): Promise<FlyerItem[]> {
    const cacheKey = `${CACHE_PREFIX.FLYER_ITEMS}:${flyerId}`;

    return cacheService.getOrSet<FlyerItem[]>(
      cacheKey,
      async () => {
        try {
          const res = await this.db.query<FlyerItem>(
            'SELECT * FROM public.flyer_items WHERE flyer_id = $1 ORDER BY flyer_item_id ASC',
            [flyerId],
          );
          return res.rows;
        } catch (error) {
          handleDbError(
            error,
            logger,
            'Database error in getFlyerItems',
            { flyerId },
            {
              defaultMessage: 'Failed to retrieve flyer items from database.',
            },
          );
        }
      },
      { ttl: CACHE_TTL.FLYER_ITEMS, logger },
    );
  }

  /**
   * Retrieves all flyer items for a given list of flyer IDs.
   * @param flyerIds An array of flyer IDs.
   * @returns A promise that resolves to an array of all matching FlyerItem objects.
   */
  async getFlyerItemsForFlyers(flyerIds: number[], logger: Logger): Promise<FlyerItem[]> {
    try {
      const res = await this.db.query<FlyerItem>(
        'SELECT * FROM public.flyer_items WHERE flyer_id = ANY($1::int[]) ORDER BY flyer_id, flyer_item_id ASC',
        [flyerIds],
      );
      return res.rows;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in getFlyerItemsForFlyers',
        { flyerIds },
        {
          defaultMessage: 'Failed to retrieve flyer items in batch from database.',
        },
      );
    }
  }

  /**
   * Counts the total number of flyer items for a given list of flyer IDs.
   * @param flyerIds An array of flyer IDs.
   * @returns A promise that resolves to the total count of items.
   */
  async countFlyerItemsForFlyers(flyerIds: number[], logger: Logger): Promise<number> {
    try {
      if (flyerIds.length === 0) {
        return 0;
      }
      const res = await this.db.query<{ count: string }>(
        'SELECT COUNT(*) FROM public.flyer_items WHERE flyer_id = ANY($1::int[])',
        [flyerIds],
      );
      return parseInt(res.rows[0].count, 10);
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in countFlyerItemsForFlyers',
        { flyerIds },
        {
          defaultMessage: 'Failed to count flyer items in batch from database.',
        },
      );
    }
  }
 
  /**
   * Finds a single flyer by its SHA-256 checksum.
   * @param checksum The checksum of the flyer file to find.
   * @returns A promise that resolves to the Flyer object or undefined if not found.
   */
  async findFlyerByChecksum(checksum: string, logger: Logger): Promise<Flyer | undefined> {
    try {
      const res = await this.db.query<Flyer>('SELECT * FROM public.flyers WHERE checksum = $1', [
        checksum,
      ]);
      return res.rows[0];
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in findFlyerByChecksum',
        { checksum },
        {
          defaultMessage: 'Failed to find flyer by checksum in database.',
        },
      );
    }
  }

  /**
   * Tracks a user interaction (view or click) for a specific flyer item.
   * This is a "fire-and-forget" operation from the client's perspective, so errors are logged but not re-thrown.
   * @param flyerItemId The ID of the flyer item.
   * @param interactionType The type of interaction, either 'view' or 'click'.
   */
  async trackFlyerItemInteraction(
    flyerItemId: number,
    interactionType: 'view' | 'click',
    logger: Logger,
  ): Promise<void> {
    try {
      // Choose the column to increment based on the interaction type.
      // This is safe from SQL injection as the input is strictly controlled to be 'view' or 'click'.
      const columnToIncrement = interactionType === 'view' ? 'view_count' : 'click_count';

      const query = `
        UPDATE public.flyer_items
        SET ${columnToIncrement} = ${columnToIncrement} + 1
        WHERE flyer_item_id = $1;
      `;
      await this.db.query(query, [flyerItemId]);
    } catch (error) {
      logger.error(
        { err: error, flyerItemId, interactionType },
        'Database error in trackFlyerItemInteraction (non-critical)',
      );
    }
  }

  /**
   * Deletes a flyer and all its associated items in a transaction.
   * This should typically be an admin-only action.
   * Invalidates related cache entries after successful deletion.
   * @param flyerId The ID of the flyer to delete.
   */
  async deleteFlyer(flyerId: number, logger: Logger): Promise<void> {
    try {
      await withTransaction(async (client) => {
        // The schema is set up with ON DELETE CASCADE for flyer_items,
        // so we only need to delete from the parent 'flyers' table.
        // The database will handle deleting associated flyer_items, unmatched_flyer_items, etc.
        const res = await client.query('DELETE FROM public.flyers WHERE flyer_id = $1', [flyerId]);
        if (res.rowCount === 0) {
          throw new NotFoundError(`Flyer with ID ${flyerId} not found.`);
        }
        logger.info(`Successfully deleted flyer with ID: ${flyerId}`);
      });
 
      // Invalidate cache after successful deletion
      await cacheService.invalidateFlyer(flyerId, logger);
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database transaction error in deleteFlyer',
        { flyerId },
        {
          defaultMessage: 'Failed to delete flyer.',
        },
      );
    }
  }
}
 
/**
 * Creates a new flyer and its associated items within a single database transaction.
 *
 * @param flyerData - The data for the flyer.
 * @param itemsForDb - An array of item data to associate with the flyer.
 * @returns An object containing the new flyer and its items.
 */
export async function createFlyerAndItems(
  flyerData: FlyerInsert,
  itemsForDb: FlyerItemInsert[],
  logger: Logger,
  client: PoolClient,
) {
  // The calling service is now responsible for managing the transaction.
  // This function assumes it is being run within a transaction via the provided client.
  const flyerRepo = new FlyerRepository(client);
 
  // 1. Find or create the store to get the store_id
  const storeId = await flyerRepo.findOrCreateStore(flyerData.store_name, logger);
 
  // 2. Prepare the data for the flyer table, replacing store_name with store_id
  const flyerDbData: FlyerDbInsert = { ...flyerData, store_id: storeId };
 
  // 3. Insert the flyer record
  const newFlyer = await flyerRepo.insertFlyer(flyerDbData, logger);
 
  // 4. Insert the associated flyer items
  const newItems = await flyerRepo.insertFlyerItems(newFlyer.flyer_id, itemsForDb, logger);
 
  return { flyer: newFlyer, items: newItems };
}