import { expect, test } from '../fixtures/auth';

test.describe('系统管理 / 角色管理', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/system/role');
    await page.getByRole('table').waitFor();
  });

  test('展示角色列表并支持筛选', async ({ page }) => {
    await expect(page.getByRole('button', { name: '新增角色' })).toBeVisible();
    await expect(page.getByText('超级管理员', { exact: true })).toBeVisible();
    await expect(page.getByText('ROLE_ADMIN')).toBeVisible();

    await page.getByPlaceholder('搜索角色名称').fill('只读');
    await expect(page.getByText('只读', { exact: true })).toBeVisible();
    await expect(page.getByText('超级管理员', { exact: true })).toHaveCount(0);
  });

  test('可新增角色', async ({ page }) => {
    await page.getByRole('button', { name: '新增角色' }).click();
    const dialog = page.getByRole('dialog', { name: '新增角色' });

    await dialog.getByLabel('角色名称').fill('审计');
    await dialog.getByLabel('角色编码').fill('ROLE_AUDIT');
    await dialog.getByLabel('描述').fill('审计只读权限');
    await dialog.getByRole('button', { name: '保 存' }).click();

    await expect(page.getByText('审计', { exact: true })).toBeVisible();
    await expect(page.getByText('角色已添加')).toBeVisible();
  });

  test('可切换状态并配置权限', async ({ page }) => {
    const statusSwitch = page.getByRole('switch', { name: '运营状态' });
    await expect(statusSwitch).toBeChecked();
    await statusSwitch.click();
    await expect(statusSwitch).not.toBeChecked();

    const row = page.getByRole('row').filter({ hasText: '运营' });
    await row.getByRole('button', { name: '权限配置' }).click();
    await expect(page.getByText('配置权限 - 运营')).toBeVisible();
    await expect(page.getByText('菜单权限')).toBeVisible();
    await expect(page.getByText('按钮权限')).toBeVisible();
    await expect(page.getByRole('treeitem', { name: '用量明细' })).toHaveAttribute('aria-checked', 'false');
    await expect(page.getByRole('treeitem', { name: '模型列表' })).toHaveAttribute('aria-checked', 'true');
    await expect(page.getByRole('checkbox', { name: 'system:user:add' })).toBeChecked();

    await page.getByRole('button', { name: '保 存' }).click();
    await expect(page.getByText('权限已保存')).toBeVisible();
  });

  test('可编辑并删除角色', async ({ page }) => {
    const row = page.getByRole('row').filter({ hasText: '只读' });
    await row.getByRole('button', { name: '编辑' }).click();
    const dialog = page.getByRole('dialog', { name: '编辑角色' });
    await dialog.getByLabel('描述').fill('只读访问，不可修改');
    await dialog.getByRole('button', { name: '保 存' }).click();
    await expect(page.getByText('只读访问，不可修改')).toBeVisible();

    await row.getByRole('button', { name: '删除' }).click();
    await page.getByRole('button', { name: '确 定' }).click();
    await expect(page.getByText('ROLE_VIEWER')).toHaveCount(0);
  });
});
