/**
 * Park Creation E2E Tests
 * 
 * Tests the complete park submission flow through the UI.
 */

import { test, expect } from '@playwright/test';
import { ParkCreationPage } from '../../helpers/page-objects/ParkCreationPage';
import { generateParkData, generateTestId } from '../../fixtures/test-data';
import { queryDatabase, cleanupTestData } from '../../fixtures/database';

test.describe('Park Creation Flow', () => {
  let parkCreationPage: ParkCreationPage;

  test.beforeEach(async ({ page }) => {
    parkCreationPage = new ParkCreationPage(page);
    await parkCreationPage.goto();
  });

  test.afterAll(async () => {
    // Clean up test data
    await cleanupTestData();
  });

  test('should create park submission successfully', async ({ page }) => {
    const parkData = generateParkData({
      name: `Test Park ${generateTestId()}`,
    });

    // Fill form
    await parkCreationPage.fillBasicInfo(parkData.name, parkData.description);
    await parkCreationPage.selectParkType(parkData.park_type);
    await parkCreationPage.selectStatus(parkData.status);
    await parkCreationPage.setOpeningDate(parkData.opened_date);

    // Submit
    await parkCreationPage.submitForm();
    await parkCreationPage.expectSuccess();

    // Verify submission created in database
    const submissions = await queryDatabase('content_submissions', (qb) =>
      qb.select('*').eq('entity_type', 'park').eq('is_test_data', true).order('created_at', { ascending: false }).limit(1)
    );

    expect(submissions).toHaveLength(1);
    expect(submissions[0].status).toBe('pending');

    // Verify NO park created yet (should be in moderation queue)
    const parks = await queryDatabase('parks', (qb) =>
      qb.select('*').eq('slug', parkData.slug)
    );

    expect(parks).toHaveLength(0);
  });

  test('should validate required fields', async ({ page }) => {
    // Try to submit empty form
    await parkCreationPage.submitForm();

    // Should show validation errors
    await parkCreationPage.expectValidationError('Name is required');
  });

  test('should auto-generate slug from name', async ({ page }) => {
    const parkName = `Amazing Theme Park ${generateTestId()}`;
    
    await page.fill('input[name="name"]', parkName);
    
    // Wait for slug to auto-generate
    await page.waitForTimeout(500);
    
    const slugValue = await page.inputValue('input[name="slug"]');
    expect(slugValue).toContain('amazing-theme-park');
    expect(slugValue).not.toContain(' '); // No spaces
  });

  test('should support custom date precision', async ({ page }) => {
    const parkData = generateParkData({
      name: `Test Park ${generateTestId()}`,
    });

    await parkCreationPage.fillBasicInfo(parkData.name, parkData.description);
    await parkCreationPage.setOpeningDate('2020-01-01', 'year');

    await parkCreationPage.submitForm();
    await parkCreationPage.expectSuccess();

    // Verify date precision in submission
    const submissions = await queryDatabase('content_submissions', (qb) =>
      qb.select('submission_data').eq('entity_type', 'park').eq('is_test_data', true).order('created_at', { ascending: false }).limit(1)
    );

    const submissionData = submissions[0].submission_data;
    expect(submissionData.opened_date_precision).toBe('year');
  });

  test('should display submission in user profile', async ({ page }) => {
    const parkData = generateParkData({
      name: `Test Park ${generateTestId()}`,
    });

    // Create submission
    await parkCreationPage.fillBasicInfo(parkData.name, parkData.description);
    await parkCreationPage.submitForm();
    await parkCreationPage.expectSuccess();

    // Navigate to user profile
    await page.click('[data-testid="user-menu"]').or(page.click('button:has-text("Profile")'));
    await page.click('text=My Submissions');

    // Verify submission appears
    await expect(page.getByText(parkData.name)).toBeVisible();
    await expect(page.getByText(/pending/i)).toBeVisible();
  });
});

test.describe('Park Form Validation', () => {
  let parkCreationPage: ParkCreationPage;

  test.beforeEach(async ({ page }) => {
    parkCreationPage = new ParkCreationPage(page);
    await parkCreationPage.goto();
  });

  test('should enforce minimum description length', async ({ page }) => {
    await page.fill('input[name="name"]', 'Test Park');
    await page.fill('textarea[name="description"]', 'Too short');

    await parkCreationPage.submitForm();
    
    await expect(page.getByText(/description.*too short/i)).toBeVisible();
  });

  test('should prevent duplicate slugs', async ({ page }) => {
    // This test would require creating a park first, then trying to create another with same slug
    // Left as TODO - requires more complex setup
  });
});
