import { test as setup, expect } from '@playwright/test';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const authFile = path.join(__dirname, '.auth/agent.json');

setup('login as CC Agent', async ({ page, request, baseURL }) => {
    // Clear any stale session lock before login
    const url = baseURL ?? 'https://ramaiah.engage.healix360.net';
    await request.post(`${url}/api/maint/unlock-agent`, {
        headers: { 'Content-Type': 'application/json', 'x-maint-otp': '400168' },
        data: { agentId: 'ramaiahadmin' },
    }).catch(() => {});

    await page.goto('/login');

    await page.locator('input[type="email"], input[name="email"], input[placeholder*="@"]').first().fill('ccagent@ramaiahcare.com');
    await page.locator('input[type="password"]').first().fill('CcRamaiah@2026');
    await page.getByRole('button', { name: 'Sign in', exact: true }).click();

    // Should land on Call Desk (/ for cc-agent role)
    await expect(page).not.toHaveURL(/\/login/, { timeout: 20_000 });

    // Sidebar should be visible
    await expect(page.locator('aside').first()).toBeVisible({ timeout: 10_000 });

    await page.context().storageState({ path: authFile });
});
