// src/tests/e2e/admin-dashboard.e2e.test.ts
import { describe, it, expect, afterAll } from 'vitest';
import supertest from 'supertest';
import app from '../../../server';
import { getPool } from '../../services/db/connection.db';

/**
 * @vitest-environment node
 */

const request = supertest(app);

describe('E2E Admin Dashboard Flow', () => {
  // Use a unique email for every run to avoid collisions
  const uniqueId = Date.now();
  const adminEmail = `e2e-admin-${uniqueId}@example.com`;
  const adminPassword = 'StrongPassword123!';

  let authToken: string;
  let adminUserId: string | null = null;

  afterAll(async () => {
    // Safety cleanup: Ensure the user is deleted from the DB if the test fails mid-way.
    if (adminUserId) {
      try {
        await getPool().query('DELETE FROM public.users WHERE user_id = $1', [adminUserId]);
      } catch (err) {
        console.error('Error cleaning up E2E admin user:', err);
      }
    }
  });

  it('should allow an admin to log in and access dashboard features', async () => {
    // 1. Register a new user (initially a regular user)
    const registerResponse = await request.post('/api/auth/register').send({
      email: adminEmail,
      password: adminPassword,
      full_name: 'E2E Admin User',
    });

    expect(registerResponse.status).toBe(201);
    const registeredUser = registerResponse.body.userprofile.user;
    adminUserId = registeredUser.user_id;
    expect(adminUserId).toBeDefined();

    // 2. Promote the user to 'admin' via direct DB access
    // (This simulates an existing admin or a manual promotion, as there is no public "register as admin" endpoint)
    await getPool().query(`UPDATE public.profiles SET role = 'admin' WHERE user_id = $1`, [
      adminUserId,
    ]);

    // 3. Login to get the access token (now with admin privileges)
    const loginResponse = await request.post('/api/auth/login').send({
      email: adminEmail,
      password: adminPassword,
    });

    expect(loginResponse.status).toBe(200);
    authToken = loginResponse.body.token;
    expect(authToken).toBeDefined();
    // Verify the role returned in the login response is now 'admin'
    expect(loginResponse.body.userprofile.role).toBe('admin');

    // 4. Fetch System Stats (Protected Admin Route)
    const statsResponse = await request
      .get('/api/admin/stats')
      .set('Authorization', `Bearer ${authToken}`);

    expect(statsResponse.status).toBe(200);
    expect(statsResponse.body).toHaveProperty('userCount');
    expect(statsResponse.body).toHaveProperty('flyerCount');

    // 5. Fetch User List (Protected Admin Route)
    const usersResponse = await request
      .get('/api/admin/users')
      .set('Authorization', `Bearer ${authToken}`);

    expect(usersResponse.status).toBe(200);
    expect(Array.isArray(usersResponse.body)).toBe(true);
    // The list should contain the admin user we just created
    const self = usersResponse.body.find((u: any) => u.user_id === adminUserId);
    expect(self).toBeDefined();

    // 6. Check Queue Status (Protected Admin Route)
    const queueResponse = await request
      .get('/api/admin/queues/status')
      .set('Authorization', `Bearer ${authToken}`);

    expect(queueResponse.status).toBe(200);
    expect(Array.isArray(queueResponse.body)).toBe(true);
    // Verify that the 'flyer-processing' queue is present in the status report
    const flyerQueue = queueResponse.body.find((q: any) => q.name === 'flyer-processing');
    expect(flyerQueue).toBeDefined();
    expect(flyerQueue.counts).toBeDefined();
  });
});