import { test, expect } from '../../fixtures/test-base';
import { loginViaUI } from '../../support/auth-helpers';
import { fillShippingAddress, TEST_SHIPPING_ADDRESS } from '../../support/checkout-helpers';
import { siteConfig } from '../../config/siteConfig';

test.describe('Addresses', () => {
    test('ADDR-001 @checkout @address: Select existing shipping address', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(120_000);
        test.skip(!siteConfig.auth.testEmail, 'Test credentials required');
        await loginViaUI(page, siteConfig.auth.testEmail!, siteConfig.auth.testPassword!);
        await addToCartAndCheckout('cotton_knit_cardigan_swing');
        const savedAddress = page.locator('[class*="saved-address" i], [class*="address-card" i], input[type="radio"][name*="address" i]').first();
        const hasAddress = await savedAddress.isVisible().catch(() => false);
        test.skip(!hasAddress, 'No saved addresses for this user');
        expect(hasAddress, 'ADDR-001: Saved address should be visible').toBeTruthy();
    });

    test('ADDR-002 @checkout @address: Enter new billing address', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(120_000);
        await addToCartAndCheckout('cotton_knit_cardigan_swing');
        await fillShippingAddress(page, TEST_SHIPPING_ADDRESS);
        // Look for billing section
        const billingSection = page.locator('[class*="billing" i], :text("Billing"), :text("請求先")').first();
        await expect(billingSection).toBeVisible({ timeout: 10000 });
    });

    test('ADDR-003 @checkout @address: Billing required for credit card', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(120_000);
        await addToCartAndCheckout('cotton_knit_cardigan_swing');
        // Try to place order without filling billing
        const placeOrderBtn = page.locator('button:has-text("Confirm"), button:has-text("Place Order"), button:has-text("注文する"), button:has-text("確認")').first();
        if (await placeOrderBtn.isVisible().catch(() => false)) {
            await placeOrderBtn.click();
            await page.waitForTimeout(2000);
            // Should see error about billing address
            const error = page.locator('[class*="error" i], [role="alert"]').first();
            const hasError = await error.isVisible().catch(() => false);
            expect(hasError, 'ADDR-003: Should show billing address error').toBeTruthy();
        }
    });

    test('ADDR-004 @checkout @address: Postal code auto-fill', async ({ page, addToCartAndCheckout }) => {
        test.setTimeout(120_000);
        await addToCartAndCheckout('cotton_knit_cardigan_swing');
        // Fill postal code and check auto-fill
        const postalInput = page.locator('input[placeholder*="郵便番号"], input[name*="postal" i], input[name*="zip" i]').first();
        await postalInput.waitFor({ state: 'visible', timeout: 15000 }).catch(() => null);
        test.skip(!(await postalInput.isVisible().catch(() => false)), 'Postal code field not found');
        await postalInput.fill('1040061');
        await page.waitForTimeout(2000);
        // Check if city/prefecture were auto-filled
        const cityInput = page.locator('input[placeholder*="市区町村"], input[name*="city" i]').first();
        const cityValue = await cityInput.inputValue().catch(() => '');
        expect(cityValue.length, 'ADDR-004: City should be auto-filled from postal code').toBeGreaterThan(0);
    });
});
