import { Given, When, Then } from '../support/fixtures';
import { storeResponse } from '../support/api-utils';
import { expect } from '@playwright/test';

// ── Background ────────────────────────────────────────────────────────────────

Given('the API is accessible', async ({ request, apiState }) => {
  try {
    await request.get(`${apiState.baseUrl}/api/health`);
  } catch {
    // Proceed even if health endpoint is not available
  }
});

// ── Authentication setup ──────────────────────────────────────────────────────

Given('I am authenticated as {string}', async ({ request, apiState }, username: string) => {
  const response = await request.post(`${apiState.baseUrl}/api/auth/login`, {
    data: { username, password: 'fellowship123' },
  });
  await storeResponse(response, apiState);
});

// ── Generic HTTP steps ────────────────────────────────────────────────────────

When('I GET {string}', async ({ request, apiState }, path: string) => {
  const response = await request.get(`${apiState.baseUrl}${path}`);
  await storeResponse(response, apiState);
});

// ── Response status assertions ────────────────────────────────────────────────

Then('the response status should be {int}', async ({ apiState }, status: number) => {
  expect(apiState.lastStatus).toBe(status);
});

Then('the response status should be less than {int}', async ({ apiState }, maxStatus: number) => {
  expect(apiState.lastStatus).toBeLessThan(maxStatus);
});

Then('the response should be successful', async ({ apiState }) => {
  expect(apiState.lastResponse!.ok()).toBeTruthy();
});

Then('the response status should be at least {int}', async ({ apiState }, minStatus: number) => {
  expect(apiState.lastStatus).toBeGreaterThanOrEqual(minStatus);
});

// ── Response body assertions ──────────────────────────────────────────────────

Then('the response body should have property {string}', async ({ apiState }, prop: string) => {
  expect(apiState.lastBody).toHaveProperty(prop);
});

Then(
  'the response body property {string} should equal {string}',
  async ({ apiState }, prop: string, value: string) => {
    expect(apiState.lastBody[prop]).toBe(value);
  }
);

Then('the response body should be an array', async ({ apiState }) => {
  expect(Array.isArray(apiState.lastBody)).toBeTruthy();
});
