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

When(
  'I log in via the API as {string} with password {string}',
  async ({ request, apiState }, username: string, password: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/auth/login`, {
      data: { username, password },
    });
    await storeResponse(response, apiState);
  }
);

When('I try to create a quest without being logged in', async ({ request, apiState }) => {
  const response = await request.post(`${apiState.baseUrl}/api/quests`, {
    data: { title: 'Unauthorized Quest' },
  });
  await storeResponse(response, apiState);
});

When('I log out via the API', async ({ request, apiState }) => {
  const response = await request.post(`${apiState.baseUrl}/api/auth/logout`);
  await storeResponse(response, apiState);
});

When(
  'I send OPTIONS to {string} with CORS origin {string}',
  async ({ request, apiState }, path: string, origin: string) => {
    const response = await request.fetch(`${apiState.baseUrl}${path}`, {
      method: 'OPTIONS',
      headers: {
        Origin: origin,
        'Access-Control-Request-Method': 'POST',
        'Access-Control-Request-Headers': 'Content-Type',
      },
    });
    await storeResponse(response, apiState);
  }
);

Then(
  'the CORS response headers should allow method {string}',
  async ({ apiState }, method: string) => {
    const corsMethod =
      apiState.lastResponse!.headers()['access-control-allow-methods'] || '';
    expect(corsMethod).toContain(method);
  }
);
