/// <reference types="cypress" />

const TEST_EMAIL = Cypress.env('TEST_EMAIL') ?? 'demo@mini-ecd.demo';
const TEST_PASSWORD = Cypress.env('TEST_PASSWORD') ?? 'Demo2024!';

// Login command met session caching — logt maar één keer in per testrun
Cypress.Commands.add('login', () => {
  cy.session('epd-user', () => {
    cy.visit('/login');
    cy.get('h2').should('contain', 'Welkom terug');
    cy.get('#email').type(TEST_EMAIL);
    cy.get('#password').type(TEST_PASSWORD);
    cy.get('button[type="submit"]').click();
    cy.url().should('match', /\/epd\//);
  });
});

// AI chat mock — onderschept de Cortex chat API
Cypress.Commands.add('mockDagnotitieChat', (patientName = 'Jan de Vries') => {
  const sseBody = [
    `data: ${JSON.stringify({ type: 'content', text: `Genoteerd.\n\n\`\`\`json\n${JSON.stringify({
      type: 'action',
      intent: 'dagnotitie',
      entities: { patientName, category: 'observatie', content: 'Patiënt voelt zich goed vandaag.' },
      confidence: 0.95,
      artifact: { type: 'dagnotitie', prefill: { patientName, category: 'observatie', content: 'Patiënt voelt zich goed vandaag.' } },
    }, null, 2)}\n\`\`\`` })}\n\n`,
    `data: ${JSON.stringify({ type: 'done' })}\n\n`,
  ].join('');

  cy.intercept('POST', '/api/cortex/chat', {
    statusCode: 200,
    headers: { 'Content-Type': 'text/event-stream' },
    body: sseBody,
  }).as('cortexChat');
});

Cypress.Commands.add('mockZoekenChat', (query = 'Jan') => {
  const sseBody = [
    `data: ${JSON.stringify({ type: 'content', text: `Even kijken.\n\n\`\`\`json\n${JSON.stringify({
      type: 'action', intent: 'zoeken',
      entities: { query }, confidence: 0.97,
      artifact: { type: 'zoeken', prefill: { query } },
    }, null, 2)}\n\`\`\`` })}\n\n`,
    `data: ${JSON.stringify({ type: 'done' })}\n\n`,
  ].join('');

  cy.intercept('POST', '/api/cortex/chat', {
    statusCode: 200,
    headers: { 'Content-Type': 'text/event-stream' },
    body: sseBody,
  }).as('cortexChat');
});

Cypress.Commands.add('mockOnbekendChat', () => {
  const sseBody = [
    `data: ${JSON.stringify({ type: 'content', text: 'Hmm, snap niet helemaal wat je bedoelt. Kun je het anders zeggen?' })}\n\n`,
    `data: ${JSON.stringify({ type: 'done' })}\n\n`,
  ].join('');

  cy.intercept('POST', '/api/cortex/chat', {
    statusCode: 200,
    headers: { 'Content-Type': 'text/event-stream' },
    body: sseBody,
  }).as('cortexChat');
});

declare global {
  namespace Cypress {
    interface Chainable {
      login(): Chainable<void>;
      mockDagnotitieChat(patientName?: string): Chainable<void>;
      mockZoekenChat(query?: string): Chainable<void>;
      mockOnbekendChat(): Chainable<void>;
    }
  }
}
