import { expect, test, type Page } from '@playwright/test';
import type { DeployPlan } from '../test-application.constants';
import { appName, eagleEyeComponent, serviceClusterUrl, uninstallComponentTime, totalTimeout } from '../test-application.constants';
import { uninstallComponent, uninstallHelmComponent } from './application';

async function waitNamespaceDeleted(page: Page, namespace = 'loki') {
    await page.getByText('资源管理').click();
    await page.getByRole('menuitem', { name: '命名空间' }).locator('span').click();
    await page.getByRole('link', { name: 'Namespace' }).click();
    const searchInput = page.getByRole('textbox', { name: /搜索.*名称/ });
    await expect
        .poll(
            async () => {
                await page.reload();
                await expect(searchInput).toBeVisible({ timeout: 60_000 });
                await searchInput.fill(namespace);
                await searchInput.press('Enter');
                const namespaceRows = page.getByRole('row').filter({ hasText: namespace });
                return namespaceRows.count();
            },
            {
                timeout: uninstallComponentTime,
                intervals: [10000, 15000, 20000],
                message: `命名空间 ${namespace} 未在预期时间内删除完成`,
            },
        )
        .toBe(0);
}

export async function cleanupAfterEach(
    page: Page,
    opts: {
        createdApps: DeployPlan[];
    },
) {
    test.setTimeout(totalTimeout);
    const { createdApps } = opts;
    const seen = new Set<string>();
    const uniqueApps = createdApps.filter((item) => {
        const key = `${item.entry}:${item.appName}`;
        if (seen.has(key)) return false;
        seen.add(key);
        return true;
    });
    const extendApps = uniqueApps.filter((item) => item.entry === 'extendManage');
    const helmApps = uniqueApps.filter((item) => item.entry === 'applicationManageHelm');

    await test.step(
        '卸载全部应用/扩展组件',
        async () => {
            if (extendApps.length) {
                await page.goto(serviceClusterUrl + '/container_platform/extendManage');
                for (const app of extendApps) {
                    await uninstallComponent(page, app.appName, {
                        strict: false,
                        quickCheckTimeoutMs: 3_000,
                    }).catch(() => {});
                }
                if (extendApps.some((app) => app.appName === appName)) {
                    await waitNamespaceDeleted(page).catch(() => {});
                }
            }
            if (helmApps.length) {
                await page.goto(serviceClusterUrl + '/container_platform/applicationManageHelm');
                for (const app of helmApps) {
                    await uninstallHelmComponent(page, app.appName, {
                        strict: false,
                        quickCheckTimeoutMs: 3_000,
                    }).catch(() => {});
                }
                if (helmApps.some((app) => app.componentName === eagleEyeComponent)) {
                    await waitNamespaceDeleted(page, 'eagle-eye').catch(() => {});
                }
            }
        },
        { timeout: uninstallComponentTime },
    );
}