import { test, expect } from '../../fixtures/test-base';
import { STRIPE_CARDS, fillStripeCard } from '../../support/payment-helpers';
import { fillShippingAddress, TEST_SHIPPING_ADDRESS, acceptTermsAndPlaceOrder, verifyOrderConfirmation } from '../../support/checkout-helpers';
import { generateTestEmail, waitForEmail, emailContains, extractLinksFromHtml } from '../../support/email-helpers';
import { loginViaUI } from '../../support/auth-helpers';
import { siteConfig } from '../../config/siteConfig';

test.describe('Payment Confirmation', () => {
    test('PAY-023 @payment @confirmation @email: Confirmation email is correct', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(180_000);
        const testEmail = generateTestEmail('order');
        const beforeOrder = new Date();

        await addToCartAndCheckout('cotton_knit_cardigan_swing');
        await fillShippingAddress(page, { ...TEST_SHIPPING_ADDRESS, email: testEmail });
        await page.waitForTimeout(1000);

        // Find and click continue/next
        const continueBtn = page.locator('button:has-text("Continue"), button:has-text("Next"), button:has-text("次へ"), button[type="submit"]').first();
        if (await continueBtn.isVisible().catch(() => false)) {
            if (!(await continueBtn.isDisabled().catch(() => true))) {
                await continueBtn.click();
                await page.waitForTimeout(2000);
            }
        }

        await fillStripeCard(page, STRIPE_CARDS.standard);
        await page.waitForTimeout(1000);
        await acceptTermsAndPlaceOrder(page);
        const confirmed = await verifyOrderConfirmation(page);
        test.skip(!confirmed, 'Order placement failed — cannot verify email');

        const email = await waitForEmail(page, testEmail, { timeoutMs: 90000, afterDate: beforeOrder });
        expect(email, 'PAY-023: Should receive confirmation email').toBeTruthy();

        if (email) {
            expect(email.subject.length, 'PAY-023: Email should have subject').toBeGreaterThan(0);
            expect(email.from, 'PAY-023: Should be from matsuyaginza').toContain('matsuyaginza');
            const hasBody = email.htmlBody.length > 0 || email.textBody.length > 0;
            expect(hasBody, 'PAY-023: Email should have body content').toBeTruthy();
        }
    });

    test('PAY-024 @payment @confirmation: Order appears in order history', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(120_000);
        test.skip(!siteConfig.auth.testEmail, 'Test credentials required');
        await loginViaUI(page, siteConfig.auth.testEmail!, siteConfig.auth.testPassword!);
        // Navigate to account orders
        await page.goto('/en/account/orders', { waitUntil: 'domcontentloaded' });
        await page.waitForLoadState('networkidle').catch(() => {});
        // Verify orders page has at least one order
        const orderLinks = page.locator('a[href*="/account/orders/"], [class*="order" i]').first();
        await expect(orderLinks).toBeVisible({ timeout: 10000 });
    });

    test('PAY-025 @payment @confirmation: Download receipt from order', async ({ page }) => {
        test.setTimeout(120_000);
        test.skip(!siteConfig.auth.testEmail, 'Test credentials required');
        await loginViaUI(page, siteConfig.auth.testEmail!, siteConfig.auth.testPassword!);
        await page.goto('/en/account/orders', { waitUntil: 'domcontentloaded' });
        await page.waitForLoadState('networkidle').catch(() => {});
        const firstOrder = page.locator('a[href*="/account/orders/"]').first();
        test.skip(!(await firstOrder.isVisible().catch(() => false)), 'No orders to download receipt from');
        await firstOrder.click();
        await page.waitForLoadState('networkidle').catch(() => {});
        const receiptBtn = page.locator('button:has-text("Receipt"), button:has-text("Invoice"), button:has-text("Download"), a:has-text("Receipt")').first();
        const hasReceipt = await receiptBtn.isVisible().catch(() => false);
        expect(hasReceipt, 'PAY-025: Receipt/invoice download should be available').toBeTruthy();
    });
});
