// src/tests/integration/server.integration.test.ts
import { describe, it, expect } from 'vitest';
import supertest from 'supertest';
import app from '../../../server';

/**
 * @vitest-environment node
 */

describe('Server Initialization Smoke Test', () => {
  it('should import the server app without crashing', () => {
    // This test's primary purpose is to ensure that all top-level code in `server.ts`
    // can execute without throwing an error. This catches issues like syntax errors,
    // bad imports, or problems with initial setup code that runs on import.
    expect(app).toBeDefined();
    expect(typeof app).toBe('function'); // An Express app is a function.
  });

  it('should respond with 200 OK and "pong" for GET /api/health/ping', async () => {
    // Use supertest to make a request to the Express app instance.
    const response = await supertest(app).get('/api/health/ping');

    // Assert that the server responds with the correct status code and body.
    // This confirms that the routing is set up correctly and the endpoint is reachable.
    expect(response.status).toBe(200);
    expect(response.text).toBe('pong');
  });

  it('should respond with 200 OK for GET /api/health/db-schema', async () => {
    // Use supertest to make a request to the Express app instance.
    const response = await supertest(app).get('/api/health/db-schema');

    // Assert that the server responds with a success message.
    // This confirms that the database connection is working and the essential tables exist.
    expect(response.status).toBe(200);
    expect(response.body).toEqual({
      success: true,
      message: 'All required database tables exist.',
    });
  });

  it('should respond with 200 OK for GET /api/health/storage', async () => {
    // Use supertest to make a request to the Express app instance.
    const response = await supertest(app).get('/api/health/storage');

    // Assert that the server responds with a success message.
    // This confirms that the directory specified by STORAGE_PATH exists and is writable
    // by the application user, which is critical for file uploads.
    expect(response.status).toBe(200);
    expect(response.body.success).toBe(true);
    expect(response.body.message).toContain('is accessible and writable');
  });

  it('should respond with 200 OK for GET /api/health/redis', async () => {
    // Use supertest to make a request to the Express app instance.
    const response = await supertest(app).get('/api/health/redis');

    // Assert that the server responds with a success message.
    // This confirms that the connection to the Redis server is active, which is
    // essential for the background job queueing system (BullMQ).
    expect(response.status).toBe(200);
    expect(response.body.success).toBe(true);
    expect(response.body.message).toBe('Redis connection is healthy.');
  });
});