/**
 * E2E Tests for Staff Contact Delete Functionality
 */

import { test, expect } from '@playwright/test';
import { prisma } from '@/lib/db';

test.describe('Staff Contact Delete', () => {
  test.beforeEach(async ({ page }) => {
    // Login as staff
    await page.goto('http://localhost:9000/staff/login');
    await page.fill('input[name="username"]', 'asim');
    await page.fill('input[name="password"]', 'AsimMawidi2025!');
    await page.click('button[type="submit"]');
    await page.waitForURL('**/staff/dashboard**');
  });

  test('should delete a single contact', async ({ page }) => {
    // Create a test contact
    const testContact = await prisma.contacts.create({
      data: {
        name: 'Test Contact for Delete',
        email: 'delete-test@example.com',
        message: 'This contact will be deleted',
        language: 'en',
        status: 'NEW',
      },
    });

    // Navigate to contacts page
    await page.goto('http://localhost:9000/staff/dashboard/contacts');

    // Wait for contacts to load
    await page.waitForSelector('text=Contact Messages');

    // Find and click delete button for the test contact
    const contactCard = page.locator(`text=${testContact.email}`).locator('..').locator('..').locator('..');
    await contactCard.locator('button:has-text("Delete")').click();

    // Confirm deletion in modal
    await expect(page.locator('text=Delete Contact')).toBeVisible();
    await expect(page.locator('text=This action cannot be undone')).toBeVisible();
    await page.click('button:has-text("Delete"):not(:has-text("Cancel"))');

    // Verify success toast
    await expect(page.locator('text=Contact deleted successfully')).toBeVisible();

    // Verify contact is removed from database
    const deletedContact = await prisma.contacts.findUnique({
      where: { id: testContact.id },
    });
    expect(deletedContact).toBeNull();
  });

  test('should cancel delete operation', async ({ page }) => {
    // Create a test contact
    const testContact = await prisma.contacts.create({
      data: {
        name: 'Test Contact Keep',
        email: 'keep-test@example.com',
        message: 'This contact will be kept',
        language: 'en',
        status: 'NEW',
      },
    });

    await page.goto('http://localhost:9000/staff/dashboard/contacts');
    await page.waitForSelector('text=Contact Messages');

    // Click delete button
    const contactCard = page.locator(`text=${testContact.email}`).locator('..').locator('..').locator('..');
    await contactCard.locator('button:has-text("Delete")').click();

    // Cancel deletion
    await expect(page.locator('text=Delete Contact')).toBeVisible();
    await page.click('button:has-text("Cancel")');

    // Verify modal is closed
    await expect(page.locator('text=Delete Contact')).not.toBeVisible();

    // Verify contact still exists
    const existingContact = await prisma.contacts.findUnique({
      where: { id: testContact.id },
    });
    expect(existingContact).not.toBeNull();

    // Cleanup
    await prisma.contacts.delete({ where: { id: testContact.id } });
  });

  test('should delete all contacts (admin only)', async ({ page }) => {
    // Create test contacts
    await prisma.contacts.createMany({
      data: [
        {
          name: 'Bulk Delete 1',
          email: 'bulk1@example.com',
          message: 'Test message 1',
          language: 'en',
          status: 'NEW',
        },
        {
          name: 'Bulk Delete 2',
          email: 'bulk2@example.com',
          message: 'Test message 2',
          language: 'en',
          status: 'NEW',
        },
      ],
    });

    await page.goto('http://localhost:9000/staff/dashboard/contacts');
    await page.waitForSelector('text=Contact Messages');

    // Verify Delete All button is visible (admin only)
    await expect(page.locator('text=Delete All Contacts')).toBeVisible();
    await page.click('button:has-text("Delete All Contacts")');

    // Verify modal and warning message
    await expect(page.locator('text=Delete All Contacts')).toBeVisible();
    await expect(page.locator('text=DANGER: This action is irreversible!')).toBeVisible();

    // Enter confirmation text
    await page.fill('input[placeholder="Type DELETE ALL"]', 'DELETE ALL');

    // Confirm deletion
    await page.click('button:has-text("Delete All Contacts"):not(:has-text("Cancel"))');

    // Verify success message
    await expect(page.locator('text=deleted successfully')).toBeVisible();

    // Verify all contacts are deleted
    const remainingContacts = await prisma.contacts.count();
    expect(remainingContacts).toBe(0);
  });

  test('should not delete all if confirmation text is wrong', async ({ page }) => {
    // Create test contact
    await prisma.contacts.create({
      data: {
        name: 'Protected Contact',
        email: 'protected@example.com',
        message: 'This should not be deleted',
        language: 'en',
        status: 'NEW',
      },
    });

    await page.goto('http://localhost:9000/staff/dashboard/contacts');
    await page.waitForSelector('text=Contact Messages');

    // Click Delete All
    await page.click('button:has-text("Delete All Contacts")');

    // Enter wrong confirmation text
    await page.fill('input[placeholder="Type DELETE ALL"]', 'delete all');

    // Delete button should be disabled
    const deleteButton = page.locator('button:has-text("Delete All Contacts"):not(:has-text("Cancel"))');
    await expect(deleteButton).toBeDisabled();

    // Cancel and verify contact still exists
    await page.click('button:has-text("Cancel")');
    const contactCount = await prisma.contacts.count();
    expect(contactCount).toBeGreaterThan(0);

    // Cleanup
    await prisma.contacts.deleteMany({});
  });

  test('should not show Delete All button for non-admin staff', async ({ page }) => {
    // Logout and login as regular staff
    await page.goto('http://localhost:9000/staff/logout');
    await page.goto('http://localhost:9000/staff/login');

    // Mock login as regular staff (you'll need to adjust based on your auth setup)
    // For now, this test documents expected behavior

    await page.goto('http://localhost:9000/staff/dashboard/contacts');

    // Regular staff should NOT see Delete All button
    // (Only admins should see it)
    // This test would need actual non-admin credentials to fully test
  });
});
