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

Given(
  'I have started a chat with character {string}',
  async ({ request, apiState }, character: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/chat/start`, {
      data: { character },
    });
    await storeResponse(response, apiState);
  }
);

When(
  'I start a chat with character {string}',
  async ({ request, apiState }, character: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/chat/start`, {
      data: { character },
    });
    await storeResponse(response, apiState);
  }
);

When(
  'I send a chat message {string} to character {string}',
  async ({ request, apiState }, message: string, character: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/chat/message`, {
      data: { character, message },
    });
    await storeResponse(response, apiState);
  }
);

When(
  'I GET the chat session for character {string}',
  async ({ request, apiState }, character: string) => {
    const response = await request.get(`${apiState.baseUrl}/api/chat/session`, {
      params: { character },
    });
    await storeResponse(response, apiState);
  }
);

When(
  'I reset the chat session for character {string}',
  async ({ request, apiState }, character: string) => {
    const response = await request.post(`${apiState.baseUrl}/api/chat/reset`, {
      data: { character },
    });
    await storeResponse(response, apiState);
  }
);

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

Then('the chat opener style should be valid', async ({ apiState }) => {
  expect(['question', 'reflection', 'directive']).toContain(apiState.lastBody.opener_style);
});

Then('the reply should not be empty', async ({ apiState }) => {
  const reply = apiState.lastBody.reply ?? apiState.lastBody.message;
  expect(reply).toBeTruthy();
  expect((reply as string).length).toBeGreaterThan(0);
});

Then('the chat reply should not be empty', async ({ apiState }) => {
  const reply = apiState.lastBody.reply ?? apiState.lastBody.message;
  expect(reply).toBeTruthy();
  expect((reply as string).length).toBeGreaterThan(0);
});

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

Then('the chat response character should be {string}', async ({ apiState }, character: string) => {
  expect(apiState.lastBody.character).toBe(character);
});

Then('the opener should not be empty', async ({ apiState }) => {
  expect(apiState.lastBody.opener).toBeTruthy();
  expect((apiState.lastBody.opener as string).length).toBeGreaterThan(0);
});
