import fs from 'node:fs';
import { expect, type Page, type TestInfo } from '@playwright/test';
import { getRuntimeQaEnv } from '../../../../src/qa/env';
export const resultDir = 'qa-results/issues/4330/dev';
export const runtime = () => getRuntimeQaEnv('dev', 'admin', 'Q4330_ADMIN');
export const active = (p: Page) => p.locator("[data-route-keep-alive-active='true']").last();
export async function navigate(p: Page, path: string) { const e = runtime(); const u = new URL(path, e.baseUrl); if (e.tenantId)
    u.searchParams.set('tenantId', e.tenantId); await p.goto(u.toString(), { waitUntil: 'domcontentloaded' }); await p.waitForTimeout(2500); }
export async function screenshot(p: Page, info: TestInfo, name: string) { await info.attach(name, { body: await p.screenshot({ animations: 'disabled', mask: [p.getByText(runtime().username!, { exact: true }), p.locator('input[type=password]')] }), contentType: 'image/png' }); }
export async function evidence(info: TestInfo, value: unknown) { await info.attach('query-evidence.json', { body: Buffer.from(JSON.stringify(value, null, 2)), contentType: 'application/json' }); }
export function record(ids: string[], detail: string, status = 'PASS') { fs.mkdirSync(resultDir, { recursive: true }); const f = resultDir + '/checks.json'; const checks = fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : {}; for (const id of ids)
    checks[id] = { status, detail }; fs.writeFileSync(f, JSON.stringify(checks, null, 2)); }
export async function profitRange(p: Page, from: string, to: string) { const r = active(p); const dates = r.locator("input[type='date']:visible"); await dates.nth(0).fill(from); await dates.nth(1).fill(to); const response = p.waitForResponse(x => new URL(x.url()).pathname === '/api/v1/profit/branch' && new URL(x.url()).searchParams.get('from') === from); await r.getByRole('button', { name: '검색', exact: true }).click(); const res = await response; expect(res.status()).toBe(200); await p.waitForTimeout(700); return (await res.json()).payload; }
export async function checkDetail(p: Page, choice: string, branch: string, occurrence = 0) {
    await active(p).locator('div[title]').filter({ has: p.getByText(branch, { exact: true }) }).nth(occurrence).click();
    const response = p.waitForResponse(r => /\/profit\/branch\/(?:lines\/)?[^?]+\/detail/.test(new URL(r.url()).pathname), { timeout: 60000 });
    const start = Date.now();
    await p.getByRole('button', { name: choice, exact: true }).click();
    const res = await response;
    expect(res.status()).toBe(200);
    const rows = (await res.json()).payload;
    const modal = p.locator('.modal.show').last();
    await expect(modal.getByText('데이터를 불러오는 중...', { exact: true })).toBeHidden({ timeout: 60000 });
    await expect(modal.locator('tbody tr')).toHaveCount(Math.max(1, rows.length));
    const text = await modal.innerText();
    const sums = { amount: rows.reduce((s: number, r: any) => s + Number(r.amount), 0), settlement: rows.reduce((s: number, r: any) => s + Number(r.settlementAmount), 0) };
    expect(text).toContain(sums.amount.toLocaleString() + '원');
    expect(text).toContain(sums.settlement.toLocaleString() + '원');
    expect(text).toContain(String(rows.length) + '건');
    expect(text).toContain('2026-10-01');
    expect(text).toContain('2026-10-21');
    for (let i = 0; i < rows.length; i++) {
        const cells = await modal.locator('tbody tr').nth(i).locator('td').allTextContents();
        const r = rows[i];
        expect(cells[0].trim()).toBe(r.vendorName);
        expect(cells[1].trim()).toBe(r.tid ?? '');
        expect(cells[2].trim()).toBe(r.approvalNo ?? '');
        expect(Number(cells[3].replace(/[^\d.-]/g, ''))).toBe(Number(r.amount));
        expect(Number(cells[4].replace(/[%\s]/g, ''))).toBe(Number(Number(r.commissionRate).toFixed(3)));
        expect(Number(cells[5].replace(/[%\s]/g, ''))).toBe(Number(Number(r.commissionDeviationRate).toFixed(3)));
        expect(cells[6].trim()).toBe(String(r.settlementDate).replace('T', ' ').slice(0, 16));
        expect(Number(cells[7].replace(/[^\d.-]/g, ''))).toBe(Number(r.settlementAmount));
    }
    return { rows, sums, ms: Date.now() - start, path: new URL(res.url()).pathname, query: new URL(res.url()).search, modal };
}
