/**
 * E2E Tests für Form Submission Flow
 *
 * Testet das Form-Builder Plugin mit E-Mail-Benachrichtigungen
 */

import { test, expect } from '@playwright/test'

test.describe('Forms API', () => {
  test('GET /api/forms returns form list', async ({ request }) => {
    const response = await request.get('/api/forms')

    // Forms require authentication, should return 401/403
    expect([200, 401, 403]).toContain(response.status())

    if (response.ok()) {
      const data = await response.json()
      expect(data).toHaveProperty('docs')
      expect(Array.isArray(data.docs)).toBe(true)
    }
  })

  test('GET /api/form-submissions requires authentication', async ({ request }) => {
    const response = await request.get('/api/form-submissions')

    expect([401, 403]).toContain(response.status())
  })
})

test.describe('Form Submission Flow', () => {
  test('POST /api/form-submissions requires form reference', async ({ request }) => {
    const response = await request.post('/api/form-submissions', {
      data: {
        submissionData: [{ field: 'email', value: 'test@example.com' }],
      },
    })

    // Should fail without proper form reference or auth
    expect([400, 401, 403]).toContain(response.status())
  })

  test('Form submission validates required fields', async ({ request }) => {
    const response = await request.post('/api/form-submissions', {
      data: {
        form: 1, // Assuming form ID
        submissionData: [], // Empty submission data
      },
    })

    // Should reject incomplete submission
    expect([400, 401, 403, 404]).toContain(response.status())
  })
})

test.describe('Form Builder Features', () => {
  test('Forms collection is accessible', async ({ request }) => {
    // Even without auth, endpoint should exist
    const response = await request.get('/api/forms')

    // Should not return 404 (endpoint exists)
    expect(response.status()).not.toBe(404)
  })

  test('Form submissions collection is accessible', async ({ request }) => {
    const response = await request.get('/api/form-submissions')

    // Should not return 404 (endpoint exists)
    expect(response.status()).not.toBe(404)
  })
})

test.describe('Form API Structure', () => {
  test('Forms API returns proper error format', async ({ request }) => {
    const response = await request.get('/api/forms')

    if (!response.ok()) {
      const data = await response.json()
      // Payload error format
      expect(data).toHaveProperty('errors')
    }
  })

  test('Form submission API returns proper error format', async ({ request }) => {
    const response = await request.post('/api/form-submissions', {
      data: {},
    })

    if (!response.ok()) {
      const data = await response.json()
      // Payload error format
      expect(data).toHaveProperty('errors')
    }
  })
})
