// src/tests/integration/deals.integration.test.ts
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import supertest from 'supertest';
import { createAndLoginUser } from '../utils/testHelpers';
import { cleanupDb } from '../utils/cleanup';

/**
 * @vitest-environment node
 *
 * Integration tests for the Deals API routes.
 * These routes were previously unmounted and are now available at /api/deals.
 */

describe('Deals API Routes Integration Tests', () => {
  let request: ReturnType<typeof supertest>;
  let authToken: string;
  const createdUserIds: string[] = [];

  beforeAll(async () => {
    vi.stubEnv('FRONTEND_URL', 'https://example.com');
    const app = (await import('../../../server')).default;
    request = supertest(app);

    // Create a user for the tests
    const { user, token } = await createAndLoginUser({
      email: `deals-user-${Date.now()}@example.com`,
      fullName: 'Deals Test User',
      request,
    });
    authToken = token;
    createdUserIds.push(user.user.user_id);
  });

  afterAll(async () => {
    vi.unstubAllEnvs();
    await cleanupDb({
      userIds: createdUserIds,
    });
  });

  describe('GET /api/deals/best-watched-prices', () => {
    it('should require authentication', async () => {
      const response = await request.get('/api/deals/best-watched-prices');

      // Passport returns 401 Unauthorized for unauthenticated requests
      expect(response.status).toBe(401);
    });

    it('should return empty array for authenticated user with no watched items', async () => {
      // The test user has no watched items by default, so should get empty array
      const response = await request
        .get('/api/deals/best-watched-prices')
        .set('Authorization', `Bearer ${authToken}`);

      expect(response.status).toBe(200);
      expect(response.body.success).toBe(true);
      expect(response.body.data).toBeInstanceOf(Array);
    });

    it('should reject invalid JWT token', async () => {
      const response = await request
        .get('/api/deals/best-watched-prices')
        .set('Authorization', 'Bearer invalid.token.here');

      expect(response.status).toBe(401);
    });

    it('should reject missing Bearer prefix', async () => {
      const response = await request
        .get('/api/deals/best-watched-prices')
        .set('Authorization', authToken);

      expect(response.status).toBe(401);
    });
  });
});
