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

// ── Setup ────────────────────────────────────────────────────────────────────

Given(
  'I have created a quest with title {string} type {string}',
  async ({ request, apiState }, title: string, type: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/quests`, {
      data: {
        title,
        description: `Test quest: ${title}`,
        status: 'Not Yet Begun',
        type,
      },
    });
    await storeResponse(response, apiState);
    apiState.context.createdQuestId = apiState.lastBody?.id;
  }
);

// ── Actions ──────────────────────────────────────────────────────────────────

When(
  'I create a quest with title {string} type {string} status {string}',
  async ({ request, apiState }, title: string, type: string, status: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/quests`, {
      data: { title, description: `Test quest: ${title}`, status, type },
    });
    await storeResponse(response, apiState);
    apiState.context.createdQuestId = apiState.lastBody?.id;
  }
);

When('I GET the created quest', async ({ request, apiState }) => {
  const id = apiState.context.createdQuestId;
  const response = await request.get(`${apiState.baseUrl}/api/quests/${id}`);
  await storeResponse(response, apiState);
});

When(
  'I update the created quest title to {string}',
  async ({ request, apiState }, newTitle: string) => {
    const id = apiState.context.createdQuestId;
    const response = await request.put(`${apiState.baseUrl}/api/quests/${id}`, {
      data: { title: newTitle, status: 'The Road Goes Ever On...' },
    });
    await storeResponse(response, apiState);
  }
);

When('I delete the created quest', async ({ request, apiState }) => {
  const id = apiState.context.createdQuestId;
  const response = await request.delete(`${apiState.baseUrl}/api/quests/${id}`);
  await storeResponse(response, apiState);
});

When('I complete the created quest', async ({ request, apiState }) => {
  const id = apiState.context.createdQuestId;
  const response = await request.put(`${apiState.baseUrl}/api/quests/${id}/complete`, {
    data: {},
  });
  await storeResponse(response, apiState);
});
