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

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

const trainerTokens = getCachedTokens('trainer');

test.describe('Auth API', () => {
  test('POST /v1/auth/login — successful login returns tokens', async () => {
    // Verified via global setup — tokens were obtained successfully
    expect(trainerTokens.accessToken).toBeTruthy();
    expect(trainerTokens.refreshToken).toBeTruthy();
  });

  test('POST /v1/auth/login — wrong password returns 401', async ({ request }) => {
    const response = await request.post(`${API_URL}/v1/auth/login`, {
      data: {
        phone: TEST_USERS.trainer.phone,
        password: 'wrong_password',
      },
    });

    // Could be 401 (wrong password) or 429 (rate limited from global setup)
    expect([401, 429]).toContain(response.status());
  });

  test('POST /v1/auth/refresh — refreshes access token', async ({ request }) => {
    const response = await request.post(`${API_URL}/v1/auth/refresh`, {
      data: { refreshToken: trainerTokens.refreshToken },
    });

    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    expect(body.accessToken).toBeTruthy();
  });

  test('GET /v1/auth/profile — returns current user profile', async ({ request }) => {
    const response = await request.get(`${API_URL}/v1/auth/profile`, {
      headers: authHeaders(trainerTokens),
    });

    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    expect(body.phone).toBe(TEST_USERS.trainer.phone);
    expect(body.role).toBeTruthy();
  });

  test('protected endpoint without token returns 401', async ({ request }) => {
    const response = await request.get(`${API_URL}/v1/clients`, {
      headers: {},
    });

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