/*
e2e/tasks.spec.ts

This test navigates to an Angular app, submits a form, verifies the UI 
updates, and confirms the record actually exists in PostgreSQL.

Never point E2E tests at a development or production database, as 
TRUNCATE commands will wipe all existing data.

*/

import { test, expect } from '@playwright/test';
import { Client } from 'pg';

test.describe('Task Management Flow', () => {
  let dbClient: Client;

  // Connect to the test PostgreSQL database before tests run
  test.beforeAll(async () => {
    dbClient = new Client({
      connectionString: process.env.TEST_DATABASE_URL || 
      'postgresql://postgres:password@localhost:5432/myapp_test',
    });
    await dbClient.connect();
  });

  // Clean the database table before each test for isolation
  test.beforeEach(async () => {
    await dbClient.query('TRUNCATE TABLE tasks RESTART IDENTITY CASCADE');
  });

  // Close the database connection after all tests finish
  test.afterAll(async () => {
    await dbClient.end();
  });

  test('Should create a new task in Angular UI and persist it to PostgreSQL',
    async ({ page }) => {
    const taskTitle = 'Deploy Angular App';

    // 1. Navigate to the Angular application
    await page.goto('http://localhost:4200/tasks');

    // 2. Interact with the UI using resilient, user-facing locators
    await page.getByLabel('Task Title').fill(taskTitle);
    await page.getByRole('button', { name: 'Add Task' }).click();

    // 3. Assert the Angular UI updates immediately
    await expect(page.getByText(taskTitle)).toBeVisible();

    // 4. Verify the data was actually saved in PostgreSQL
    const result = await dbClient.query(
      'SELECT * FROM tasks WHERE title = $1', [taskTitle]
    );
    
    expect(result.rowCount).toBe(1);
    expect(result.rows[0].title).toBe(taskTitle);
    expect(result.rows[0].completed).toBe(false);
  });
});

