import { test, expect } from '@playwright/test';
import { getCachedTokens, authHeaders } from './helpers';

const API_URL = process.env.E2E_API_URL || 'http://localhost:3000';

const trainerTokens = getCachedTokens('trainer');
const coordinatorTokens = getCachedTokens('coordinator');
const managerTokens = getCachedTokens('manager');

test.describe('RBAC — Role-Based Access Control', () => {
  test('trainer can access own clients', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/clients`, {
      headers: authHeaders(trainerTokens),
    });
    expect(res.ok()).toBeTruthy();
  });

  test('trainer can access own funnel', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/funnel`, {
      headers: authHeaders(trainerTokens),
    });
    expect(res.ok()).toBeTruthy();
  });

  test('trainer can access schedule', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/trainings`, {
      headers: authHeaders(trainerTokens),
    });
    expect(res.ok()).toBeTruthy();
  });

  test('trainer can access stats summary', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/stats/summary`, {
      headers: authHeaders(trainerTokens),
    });
    expect(res.ok()).toBeTruthy();
  });

  test('coordinator can access all clients', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/clients`, {
      headers: authHeaders(coordinatorTokens),
    });
    expect(res.ok()).toBeTruthy();
  });

  test('manager can access reports (requires web_reports module)', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/reports`, {
      headers: authHeaders(managerTokens),
    });

    // May return 200 or 403 depending on module enablement
    expect([200, 403]).toContain(res.status());
  });

  test('trainer cannot access admin endpoints', async ({ request }) => {
    const res = await request.get(`${API_URL}/v1/clubs`, {
      headers: authHeaders(trainerTokens),
    });

    expect([401, 403, 404]).toContain(res.status());
  });
});
