/**
 * E2E Test for Staff Interview Management (Staff Perspective)
 *
 * Tests staff dashboard interview management workflow
 */

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

const BASE_URL = 'http://localhost:9000';
const STAFF_USERNAME = 'test-staff';
const STAFF_PASSWORD = 'TestStaff2025!';

test.describe('Staff Interview Management E2E', () => {
  let testStaffId: string;
  let testBookingId: string;
  let testJobId: string;
  let testApplicationId: string;

  test.beforeAll(async () => {
    // Create test staff account
    const hashedPassword = await bcrypt.hash(STAFF_PASSWORD, 12);
    const staff = await prisma.staff_accounts.create({
      data: {
        username: STAFF_USERNAME,
        password: hashedPassword,
        fullName: 'Test Staff',
        email: 'test-staff@mawidi.com',
        isActive: true,
      },
    });
    testStaffId = staff.id;

    // Create test job and application
    const job = await prisma.jobs.create({
      data: {
        title: 'Staff Test Job',
        titleAr: 'وظيفة اختبار',
        department: 'Testing',
        location: 'Doha',
        description: 'Test job',
        descriptionAr: 'وصف',
        status: 'open',
      },
    });
    testJobId = job.id;

    const application = await prisma.job_applications.create({
      data: {
        jobId: testJobId,
        applicantName: 'Test Applicant',
        applicantEmail: 'applicant@example.com',
        phoneNumber: '+97150888888',
        cvUrl: 'https://example.com/cv.pdf',
        status: 'selected',
      },
    });
    testApplicationId = application.id;

    // Create test booking
    const booking = await prisma.interview_bookings.create({
      data: {
        applicationId: testApplicationId,
        jobId: testJobId,
        applicantName: 'Test Applicant',
        applicantEmail: 'applicant@example.com',
        applicantPhone: '+97150888888',
        preferredDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
        preferredTime: '10:00:00',
        timezone: 'Asia/Qatar',
        status: 'pending',
      },
    });
    testBookingId = booking.id;
  });

  test.afterAll(async () => {
    // Cleanup
    await prisma.interview_bookings.deleteMany({
      where: { id: testBookingId },
    });
    await prisma.job_applications.deleteMany({
      where: { id: testApplicationId },
    });
    await prisma.jobs.deleteMany({
      where: { id: testJobId },
    });
    await prisma.staff_accounts.deleteMany({
      where: { id: testStaffId },
    });
  });

  test('should view and manage interview bookings', async ({ page }) => {
    // Login as staff
    await page.goto(`${BASE_URL}/staff/login`);
    await page.fill('input[name="username"]', STAFF_USERNAME);
    await page.fill('input[name="password"]', STAFF_PASSWORD);
    await page.click('button[type="submit"]');

    // Wait for dashboard
    await page.waitForURL(/\/staff\/dashboard/);

    // Navigate to interviews section
    await page.goto(`${BASE_URL}/staff/dashboard/careers/interviews`);

    // Verify interviews list loads
    await expect(page.locator('h1')).toContainText('Interview Bookings');

    // Find test booking
    await expect(page.locator(`text=${testBookingId}`)).toBeVisible({ timeout: 5000 });

    // Click on booking to view details
    await page.click(`text=${testBookingId}`);

    // Verify booking details page
    await expect(page.locator('text=Test Applicant')).toBeVisible();
    await expect(page.locator('text=Staff Test Job')).toBeVisible();

    // Add meeting link
    await page.fill('input[name="meetingLink"]', 'https://zoom.us/j/123456789');
    
    // Confirm interview
    await page.click('button:has-text("Confirm Interview")');

    // Should show success message
    await expect(page.locator('text=/confirmed/i')).toBeVisible({ timeout: 5000 });

    // Verify status in database
    const updatedBooking = await prisma.interview_bookings.findUnique({
      where: { id: testBookingId },
    });

    expect(updatedBooking?.status).toBe('confirmed');
    expect(updatedBooking?.meetingLink).toBe('https://zoom.us/j/123456789');
  });

  test('should filter bookings by status', async ({ page }) => {
    // Login
    await page.goto(`${BASE_URL}/staff/login`);
    await page.fill('input[name="username"]', STAFF_USERNAME);
    await page.fill('input[name="password"]', STAFF_PASSWORD);
    await page.click('button[type="submit"]');
    await page.waitForURL(/\/staff\/dashboard/);

    // Navigate to interviews
    await page.goto(`${BASE_URL}/staff/dashboard/careers/interviews`);

    // Filter by pending status
    await page.selectOption('select[name="status"]', 'pending');
    await page.click('button:has-text("Filter")');

    // Should show only pending bookings
    await expect(page.locator('tr:has-text("pending")')).toBeVisible();
  });

  test('should add staff notes to booking', async ({ page }) => {
    // Login
    await page.goto(`${BASE_URL}/staff/login`);
    await page.fill('input[name="username"]', STAFF_USERNAME);
    await page.fill('input[name="password"]', STAFF_PASSWORD);
    await page.click('button[type="submit"]');
    await page.waitForURL(/\/staff\/dashboard/);

    // Navigate to booking details
    await page.goto(`${BASE_URL}/staff/dashboard/careers/interviews/${testBookingId}`);

    // Add staff notes
    await page.fill('textarea[name="staffNotes"]', 'Candidate shows strong technical skills. Recommend proceeding.');
    await page.click('button:has-text("Save Notes")');

    // Should show success message
    await expect(page.locator('text=/saved/i')).toBeVisible({ timeout: 5000 });

    // Verify in database
    const booking = await prisma.interview_bookings.findUnique({
      where: { id: testBookingId },
    });

    expect(booking?.staffNotes).toContain('strong technical skills');
  });
});
