import { http, HttpResponse } from 'msw'
import { test, expect } from './msw-setup'

test.describe('US-1: Create an event', () => {
  test('shows validation errors for empty required fields', async ({ page }) => {
    await page.goto('/create')

    await page.getByRole('button', { name: /create event/i }).click()

    await expect(page.getByText('Title is required.')).toBeVisible()
    await expect(page.getByText('Date and time are required.')).toBeVisible()
  })

  test('creates an event and redirects to event detail page', async ({ page }) => {
    await page.goto('/create')

    await page.getByLabel(/title/i).fill('Summer BBQ')
    await page.getByLabel(/description/i).fill('Bring your own drinks')
    await page.getByLabel(/date/i).first().fill('2026-04-15T18:00')
    await page.getByLabel(/location/i).fill('Central Park')

    await page.getByRole('button', { name: /create event/i }).click()

    await expect(page).toHaveURL(/\/events\/.+/)
  })

  test('stores event data in localStorage after creation', async ({ page }) => {
    await page.goto('/create')

    await page.getByLabel(/title/i).fill('Summer BBQ')
    await page.getByLabel(/date/i).first().fill('2026-04-15T18:00')

    await page.getByRole('button', { name: /create event/i }).click()
    await expect(page).toHaveURL(/\/events\/.+/)

    const storage = await page.evaluate(() => {
      const raw = localStorage.getItem('fete:events')
      return raw ? JSON.parse(raw) : null
    })
    expect(storage).not.toBeNull()
    expect(storage).toHaveLength(1)
    expect(storage[0]).toHaveProperty('eventToken')
    expect(storage[0]).toHaveProperty('title')
  })

  test('shows server error on API failure', async ({ page, network }) => {
    network.use(
      http.post('*/api/events', () => {
        return HttpResponse.json(
          { title: 'Bad Request', status: 400, detail: 'Validation failed' },
          { status: 400, headers: { 'Content-Type': 'application/problem+json' } },
        )
      }),
    )

    await page.goto('/create')
    await page.getByLabel(/title/i).fill('Test')
    await page.getByLabel(/date/i).first().fill('2026-04-15T18:00')

    await page.getByRole('button', { name: /create event/i }).click()

    await expect(page.getByRole('alert')).toBeVisible()
  })
})
