import { test, expect } from '@playwright/test';
import { loginToJamUI, createAndJoinSession } from '../utils/test-helpers';

test.describe('Session Settings Modal', () => {
  test.beforeEach(async ({ page }) => {
    await loginToJamUI(page);
    await createAndJoinSession(page);
  });

  test('INT-01: Settings button opens modal', async ({ page }) => {
    // Locate Settings button by the gear icon alt text
    const settingsButton = page.locator('img[alt="Settings"]');
    await expect(settingsButton).toBeVisible();

    // Click the Settings button
    await settingsButton.click();

    // Verify modal opens - use privacy select as the indicator (unique to modal)
    // The modal header text "Session Settings" can also appear in toasts
    const privacySelect = page.locator('[data-testid="session-privacy"]');
    await expect(privacySelect).toBeVisible({ timeout: 5000 });

    // Description textarea
    const descriptionTextarea = page.locator('textarea[name="description"]');
    await expect(descriptionTextarea).toBeVisible();

    // Save button within the modal
    const saveButton = page.locator('.modal-footer button:has-text("Save")');
    await expect(saveButton).toBeVisible();

    // Cancel button within the modal
    const cancelButton = page.locator('.modal-footer button:has-text("Cancel")');
    await expect(cancelButton).toBeVisible();
  });

  test('INT-02: Save settings makes PUT /sessions/{id} API call', async ({ page }) => {
    // Setup API interception to capture the PUT request
    let capturedRequest: { url: string; method: string; body: any } | null = null;

    await page.route('**/api/sessions/*', async (route, request) => {
      if (request.method() === 'PUT') {
        capturedRequest = {
          url: request.url(),
          method: request.method(),
          body: JSON.parse(request.postData() || '{}')
        };
      }
      await route.continue();
    });

    // Open Settings modal
    const settingsButton = page.locator('img[alt="Settings"]');
    await settingsButton.click();

    // Wait for modal to open - use privacy select as the indicator (unique to modal)
    const privacySelect = page.locator('[data-testid="session-privacy"]');
    await expect(privacySelect).toBeVisible({ timeout: 5000 });

    // Modify form values
    // Change privacy to public (value="1" based on SESSION_PRIVACY_MAP)
    await privacySelect.selectOption('1');

    // Change description
    const descriptionTextarea = page.locator('textarea[name="description"]');
    await descriptionTextarea.fill('Updated test description');

    // Click Save button within the modal
    const saveButton = page.locator('.modal-footer button:has-text("Save")');
    await saveButton.click();

    // Wait for API call to complete
    await page.waitForTimeout(2000);

    // Verify API call was made
    expect(capturedRequest).not.toBeNull();
    expect(capturedRequest?.method).toBe('PUT');
    expect(capturedRequest?.url).toMatch(/\/api\/sessions\/[a-f0-9-]+$/);
    expect(capturedRequest?.body).toHaveProperty('description', 'Updated test description');

    // Verify privacy-related fields are included in the payload
    // When privacy is "public" (value=1): musician_access=true, approval_required=false
    expect(capturedRequest?.body).toHaveProperty('musician_access');
    expect(capturedRequest?.body).toHaveProperty('approval_required');

    // Verify modal closes after save - check privacy select is no longer visible
    await expect(privacySelect).not.toBeVisible({ timeout: 5000 });
  });

  test('INT-03: Cancel closes modal without API call', async ({ page }) => {
    // Setup API tracking to detect any PUT calls
    let apiCallMade = false;

    await page.route('**/api/sessions/*', async (route, request) => {
      if (request.method() === 'PUT') {
        apiCallMade = true;
      }
      await route.continue();
    });

    // Open Settings modal
    const settingsButton = page.locator('img[alt="Settings"]');
    await settingsButton.click();

    // Verify modal is open - use privacy select as the indicator
    const privacySelect = page.locator('[data-testid="session-privacy"]');
    await expect(privacySelect).toBeVisible({ timeout: 5000 });

    // Optionally modify form values (to ensure cancel truly discards changes)
    const descriptionTextarea = page.locator('textarea[name="description"]');
    await descriptionTextarea.fill('This should be discarded');

    // Click Cancel button
    const cancelButton = page.locator('.modal-footer button:has-text("Cancel")');
    await cancelButton.click();

    // Verify modal closes - privacy select should no longer be visible
    await expect(privacySelect).not.toBeVisible({ timeout: 5000 });

    // Verify NO API call was made
    expect(apiCallMade).toBe(false);
  });
});
