import { test, expect, type Page } from '@playwright/test';
import {
    BASE_URL, AGENT, AGENT2, SUB_AGENT, loginAs, registerUserWithReferralCode,
} from '../helpers';

// Agent Portal — demoting an agent/sub-agent back to a plain player.
// Uses freshly registered players under the seeded master AGENT (ABCDEF01)
// and regular AGENT2 (AGENT2REF) so no other spec's fixtures change role.

const MASTER_CODE = 'ABCDEF01';
const AGENT2_CODE = 'AGENT2REF';

async function promoteReferredPlayer(
    page: Page,
    referrer: { mobile: string; password: string },
    playerMobile: string,
): Promise<void> {
    await loginAs(page, referrer.mobile, referrer.password);
    await page.goto(`${BASE_URL}/agent/users?search=${encodeURIComponent(playerMobile)}`);

    const row = page.locator('[data-testid^="agent-user-row-"]').filter({ hasText: playerMobile });
    await expect(row).toBeVisible();
    await row.locator('[data-testid^="btn-promote-agent-"]').click();

    await expect(page.locator('[data-testid="promote-agent-modal"]')).toBeVisible();
    // The form caps the rate at the upline's own rate, which is 0 for the
    // AGENT2 fixture, so 0 is the only value valid for both cases.
    await page.fill('[data-testid="input-promote-commission-rate"]', '0');
    await page.click('[data-testid="btn-confirm-promote"]');

    await expect(page.locator('[data-testid="flash-success"]')).toContainText('has been promoted');
}

async function demoteOnAgentsPage(page: Page, playerMobile: string): Promise<string> {
    await page.goto(`${BASE_URL}/agent/agents?search=${encodeURIComponent(playerMobile)}`);

    const row = page.locator('[data-testid^="agent-agents-row-"]').filter({ hasText: playerMobile });
    await expect(row).toBeVisible();
    const id = ((await row.getAttribute('data-testid')) ?? '').replace('agent-agents-row-', '');

    await page.locator(`[data-testid="btn-demote-agent-${id}"]`).click();
    await expect(page.locator('[data-testid="demote-agent-modal"]')).toBeVisible();
    await page.click('[data-testid="btn-confirm-demote"]');

    await expect(page.locator('[data-testid="flash-success"]')).toContainText('has been demoted to Player');
    return id;
}

async function expectBackToPlayer(page: Page, player: { mobile: string; password: string }): Promise<void> {
    await loginAs(page, player.mobile, player.password);
    await page.goto(`${BASE_URL}/agent/dashboard`);
    await expect(page.locator('[data-testid="agent-dashboard-title"]')).not.toBeVisible();
}

test.describe('Agent Portal — Demote to Player', () => {
    test.setTimeout(150_000);

    test('a master agent can demote one of their agents back to a player', async ({ page }) => {
        const player = await registerUserWithReferralCode(page, MASTER_CODE);

        await promoteReferredPlayer(page, AGENT, player.mobile);
        const id = await demoteOnAgentsPage(page, player.mobile);

        // The demoted user is no longer listed under My Agents...
        await page.goto(`${BASE_URL}/agent/agents?search=${encodeURIComponent(player.mobile)}`);
        await expect(page.locator(`[data-testid="agent-agents-row-${id}"]`)).toHaveCount(0);

        // ...and can no longer reach the agent portal.
        await expectBackToPlayer(page, player);

        // Existing referred players are untouched: the demoted user stays as
        // the player's referrer, so they show up under My Referrals again.
        await loginAs(page, AGENT.mobile, AGENT.password);
        await page.goto(`${BASE_URL}/agent/users?search=${encodeURIComponent(player.mobile)}`);
        await expect(page.locator('[data-testid^="agent-user-row-"]').filter({ hasText: player.mobile })).toBeVisible();
    });

    test('a regular agent can demote one of their sub-agents back to a player', async ({ page }) => {
        const player = await registerUserWithReferralCode(page, AGENT2_CODE);

        await promoteReferredPlayer(page, AGENT2, player.mobile);
        const id = await demoteOnAgentsPage(page, player.mobile);

        await page.goto(`${BASE_URL}/agent/agents?search=${encodeURIComponent(player.mobile)}`);
        await expect(page.locator(`[data-testid="agent-agents-row-${id}"]`)).toHaveCount(0);

        await expectBackToPlayer(page, player);
    });

    test('a sub-agent has no agents of their own and sees no demote action', async ({ page }) => {
        await loginAs(page, SUB_AGENT.mobile, SUB_AGENT.password);
        await page.goto(`${BASE_URL}/agent/agents`);
        await expect(page.locator('[data-testid^="btn-demote-agent-"]')).toHaveCount(0);
    });
});
