// src/tests/integration/db.integration.test.ts
import { describe, it, expect } from 'vitest';
import * as db from '../../services/db/index.db';
import * as bcrypt from 'bcrypt';
import { getPool } from '../../services/db/connection.db';

describe('Database Service Integration Tests', () => {
  it('should create a new user and be able to find them by email', async ({ onTestFinished }) => {
    // Arrange: Use a unique email for each test run to ensure isolation.
    const email = `test.user-${Date.now()}@example.com`;
    const password = 'password123';
    const fullName = 'Test User';
    const saltRounds = 10;
    const passwordHash = await bcrypt.hash(password, saltRounds);

    // Ensure the created user is cleaned up after this specific test finishes.
    onTestFinished(async () => {
      await getPool().query('DELETE FROM public.users WHERE email = $1', [email]);
    });

    // Act: Call the createUser function
    const createdUser = await db.userRepo.createUser(email, passwordHash, { full_name: fullName });

    // Assert: Check that the user was created with the correct details
    expect(createdUser).toBeDefined();
    expect(createdUser.user.email).toBe(email);
    expect(createdUser.user_id).toBeTypeOf('string');

    // Act: Try to find the user we just created
    const foundUser = await db.userRepo.findUserByEmail(email);

    // Assert: Check that the found user matches the created user
    expect(foundUser).toBeDefined();
    expect(foundUser?.user_id).toBe(createdUser.user_id);
    expect(foundUser?.email).toBe(email);

    // Also, verify the profile was created by the trigger
    const profile = await db.userRepo.findUserProfileById(createdUser.user_id);
    expect(profile).toBeDefined();
    expect(profile?.full_name).toBe(fullName);
  });
});