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');

test.describe('Clients API', () => {
  test('GET /v1/clients — returns paginated client list', async ({ request }) => {
    const response = await request.get(`${API_URL}/v1/clients`, {
      headers: authHeaders(trainerTokens),
    });

    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    expect(body.data).toBeInstanceOf(Array);
    expect(body).toHaveProperty('hasMore');
  });

  test('POST /v1/clients — creates a new client (coordinator)', async ({ request }) => {
    const uniquePhone = `+7900${Date.now().toString().slice(-7)}`;

    const response = await request.post(`${API_URL}/v1/clients`, {
      headers: authHeaders(coordinatorTokens),
      data: {
        firstName: 'Тест',
        lastName: 'Клиент',
        phone: uniquePhone,
      },
    });

    expect(response.ok()).toBeTruthy();
    const client = await response.json();
    expect(client.id).toBeTruthy();
    expect(client.firstName).toBe('Тест');
    expect(client.lastName).toBe('Клиент');
    expect(client.phone).toBe(uniquePhone);
  });

  test('POST /v1/clients — trainer cannot create clients', async ({ request }) => {
    const response = await request.post(`${API_URL}/v1/clients`, {
      headers: authHeaders(trainerTokens),
      data: {
        firstName: 'Тест',
        lastName: 'Отказ',
        phone: '+79009999998',
      },
    });

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

  test('GET /v1/clients/:id — returns client by id', async ({ request }) => {
    // Create first (as coordinator)
    const uniquePhone = `+7900${Date.now().toString().slice(-7)}`;
    const createRes = await request.post(`${API_URL}/v1/clients`, {
      headers: authHeaders(coordinatorTokens),
      data: {
        firstName: 'Деталь',
        lastName: 'Тест',
        phone: uniquePhone,
      },
    });
    const created = await createRes.json();

    // Fetch by id (as coordinator)
    const response = await request.get(`${API_URL}/v1/clients/${created.id}`, {
      headers: authHeaders(coordinatorTokens),
    });

    expect(response.ok()).toBeTruthy();
    const client = await response.json();
    expect(client.id).toBe(created.id);
  });

  test('clients are isolated by club_id — trainer cannot see other club clients', async ({
    request,
  }) => {
    const response = await request.get(`${API_URL}/v1/clients`, {
      headers: authHeaders(trainerTokens),
    });

    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    expect(body.data).toBeInstanceOf(Array);
  });
});
