// src/tests/integration/shopping-list.integration.test.ts
import { describe, it, expect } from 'vitest';
import * as db from '../../services/db/index.db'; // This was missing
import * as bcrypt from 'bcrypt';
import { getPool } from '../../services/db/connection.db';
import type { ShoppingList } from '../../types';

describe('Shopping List DB Service Tests', () => {
  it('should create and retrieve a shopping list for a user', async ({ onTestFinished }) => {
    // Arrange: Create a fresh user for this specific test.
    const email = `list-user-${Date.now()}@example.com`;
    const passwordHash = await bcrypt.hash('password123', 10);
    const user = await db.userRepo.createUser(email, passwordHash, { full_name: 'List Test User' });
    const testUserId = user.user_id;

    onTestFinished(async () => {
      await getPool().query('DELETE FROM public.users WHERE user_id = $1', [testUserId]);
    });

    // Arrange: The `beforeEach` hook already creates a user, which in turn
    // triggers the creation of a "Main Shopping List". We then create two more.
    await db.shoppingRepo.createShoppingList(testUserId, 'Weekly Groceries');
    await db.shoppingRepo.createShoppingList(testUserId, 'Party Supplies');

    // Act: Fetch the shopping lists for that user
    const lists = await db.shoppingRepo.getShoppingLists(testUserId);

    // Assert: We expect to find 3 lists: the default one and the two we just created.
    expect(lists).toBeDefined();
    expect(lists).toHaveLength(3);
    expect(lists.some((list: ShoppingList) => list.name === 'Main Shopping List')).toBe(true);
    expect(lists.some((list: ShoppingList) => list.name === 'Weekly Groceries')).toBe(true);
    expect(lists.some((list: ShoppingList) => list.name === 'Party Supplies')).toBe(true);
  });

  it('should not retrieve shopping lists belonging to another user', async ({ onTestFinished }) => {
    // Arrange: Create a fresh user for this specific test.
    const email = `privacy-user-${Date.now()}@example.com`;
    const passwordHash = await bcrypt.hash('password123', 10);
    const user = await db.userRepo.createUser(email, passwordHash, { full_name: 'Privacy Test User' });
    const testUserId = user.user_id;

    onTestFinished(async () => {
      await getPool().query('DELETE FROM public.users WHERE user_id = $1', [testUserId]);
    });

    // Arrange: Create a list for our primary test user
    await db.shoppingRepo.createShoppingList(testUserId, 'My Private List');

    // Act: Fetch lists for a DIFFERENT user ID (one that doesn't exist)
    const otherUserId = '00000000-0000-0000-0000-000000000000';
    const lists = await db.shoppingRepo.getShoppingLists(otherUserId);

    // Assert: Ensure no lists were returned
    expect(lists).toBeDefined();
    expect(lists).toHaveLength(0);
  });
});