// src/tests/e2e/admin-authorization.e2e.test.ts
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import * as apiClient from '../../services/apiClient';
import { cleanupDb } from '../utils/cleanup';
import { createAndLoginUser } from '../utils/testHelpers';
import type { UserProfile } from '../../types';

/**
 * @vitest-environment node
 */
describe('Admin Route Authorization', () => {
  let regularUser: UserProfile;
  let regularUserAuthToken: string;

  beforeAll(async () => {
    // Create a standard user for testing authorization
    const { user, token } = await createAndLoginUser({
      email: `e2e-authz-user-${Date.now()}@example.com`,
      fullName: 'E2E AuthZ User',
    });
    regularUser = user;
    regularUserAuthToken = token;
  });

  afterAll(async () => {
    // Cleanup the created user
    if (regularUser?.user.user_id) {
      await cleanupDb({ userIds: [regularUser.user.user_id] });
    }
  });

  // Define a list of admin-only endpoints to test
  const adminEndpoints = [
    {
      method: 'GET',
      path: '/admin/stats',
      action: (token: string) => apiClient.getApplicationStats(token),
    },
    {
      method: 'GET',
      path: '/admin/users',
      action: (token: string) => apiClient.authedGet('/admin/users', { tokenOverride: token }),
    },
    {
      method: 'GET',
      path: '/admin/corrections',
      action: (token: string) => apiClient.getSuggestedCorrections(token),
    },
    {
      method: 'POST',
      path: '/admin/corrections/1/approve',
      action: (token: string) => apiClient.approveCorrection(1, token),
    },
    {
      method: 'POST',
      path: '/admin/trigger/daily-deal-check',
      action: (token: string) =>
        apiClient.authedPostEmpty('/admin/trigger/daily-deal-check', { tokenOverride: token }),
    },
    {
      method: 'GET',
      path: '/admin/queues/status',
      action: (token: string) =>
        apiClient.authedGet('/admin/queues/status', { tokenOverride: token }),
    },
  ];

  it.each(adminEndpoints)(
    'should return 403 Forbidden for a regular user trying to access $method $path',
    async ({ action }) => {
      // Act: Attempt to access the admin endpoint with the regular user's token
      const response = await action(regularUserAuthToken);

      // Assert: The request should be forbidden
      expect(response.status).toBe(403);
      const responseBody = await response.json();
      expect(responseBody.error.message).toBe('Forbidden: Administrator access required.');
    },
  );
});
