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

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

Given('there are items available in the shop', async ({ request, apiState }) => {
  const response = await request.get(`${apiState.baseUrl}/api/shop/items`);
  await storeResponse(response, apiState);
  const items: any[] = apiState.lastBody?.items ?? [];
  expect(items.length).toBeGreaterThan(0);
  apiState.context.shopItems = items;
});

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

When('I GET the first shop item by ID', async ({ request, apiState }) => {
  const items: any[] = apiState.context.shopItems;
  const itemId = items[0].id;
  apiState.context.lastItemId = itemId;
  const response = await request.get(`${apiState.baseUrl}/api/shop/items/${itemId}`);
  await storeResponse(response, apiState);
});

// ── Assertions ────────────────────────────────────────────────────────────────

Then('the gold balance should be a non-negative number', async ({ apiState }) => {
  expect(typeof apiState.lastBody.gold).toBe('number');
  expect(apiState.lastBody.gold).toBeGreaterThanOrEqual(0);
});

Then('inventory items should have price fields when present', async ({ apiState }) => {
  const items: any[] = apiState.lastBody?.inventory ?? [];
  items.forEach((item: any) => {
    expect(item).toHaveProperty('id');
    expect(item).toHaveProperty('name');
  });
});

Then('the shop items should be a non-empty array', async ({ apiState }) => {
  const items: any[] = apiState.lastBody?.items ?? [];
  expect(Array.isArray(items)).toBeTruthy();
  expect(items.length).toBeGreaterThan(0);
});

Then('the shop item should have name and id', async ({ apiState }) => {
  const item = apiState.lastBody?.item ?? apiState.lastBody;
  expect(item).toHaveProperty('id');
  expect(item).toHaveProperty('name');
});
